A side effect is any operation that reaches outside the pure render cycle — fetching data from an API, subscribing to a WebSocket, manually manipulating the DOM, or setting a document title. React’s render function must remain pure (no side effects directly inside the function body), soDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/Byrontosh/FundamentosReact/llms.txt
Use this file to discover all available pages before exploring further.
useEffect provides a dedicated escape hatch. It accepts a callback that React runs after the component has painted to the screen, keeping your UI responsive. An optional cleanup function can be returned from the callback to tear down subscriptions or cancel pending requests when the component unmounts or before the effect re-runs.
Hook signature
- The first argument is the effect callback. Any value it returns must be a cleanup function (or nothing).
- The second argument is the dependency array, which controls when the effect re-runs.
- The cleanup function (the return value) runs before the next invocation of the same effect and when the component unmounts — it is the right place to cancel fetches, clear timers, or unsubscribe from event listeners.
Dependency array behavior
| Dependency array | When the effect runs |
|---|---|
[] — empty array | Once, immediately after the component mounts. Equivalent to componentDidMount in class components. |
[dep] — one or more specific dependencies | On mount and whenever any listed dependency changes between renders. |
| (no array) | After every render. Use sparingly — it is rarely what you want and can cause infinite loops if the effect itself updates state. |
API fetch demo
TheTercero component fetches a random user from the JSONPlaceholder API and displays their profile. The state variable buscar acts as a manual trigger: placing it in the dependency array means the effect re-runs — and a fresh random user is fetched — every time buscar changes. Because the demo currently mounts with buscar set to 1 and never calls setBuscar, the fetch fires exactly once on mount. Extending the UI with a “Buscar otro” button that increments buscar would immediately trigger another fetch without any extra wiring.
getUserIDApi is defined inside the component. When you define an async helper inside the effect or the component body and reference it from the effect, the React linting rules (eslint-plugin-react-hooks) will ask you to add it to the dependency array or move it inside the effect callback. Keeping the function inside the useEffect callback itself is the safest pattern for one-off fetch calls, as it avoids the dependency entirely.
