useEffect lets a component run code after it renders: fetch data, subscribe to events, start a timer or update the page title. It is also the hook most often misused. This guide explains how it works and the mistakes to avoid.
The basic shape
useEffect(() => {
document.title = `Hello ${name}`;
}, [name]);The function runs after the component renders. The array at the end is the dependency array. React runs the effect again only if a value in that array changed since the last render.
Three forms of the dependency array
useEffect(fn)with no array: runs after every render.useEffect(fn, [])with an empty array: runs after the first render only (and twice in development with Strict Mode, on purpose).useEffect(fn, [a, b]): runs after the first render and wheneveraorbchanges.
Cleanup: undoing what the effect did
Return a function to clean up. React calls it before running the effect again and when the component unmounts.
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id);
}, []);Without cleanup, timers, event listeners and subscriptions keep running after the component is gone, causing leaks and bugs.
Fetching data safely
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${id}`, { signal: controller.signal })
.then((r) => r.json())
.then(setUser)
.catch((e) => { if (e.name !== 'AbortError') setError(e); });
return () => controller.abort();
}, [id]);Aborting in the cleanup stops an old request from overwriting the result of a newer one when id changes quickly.
Common mistakes
- Missing dependencies. If the effect uses a value, list it. The ESLint rule
react-hooks/exhaustive-depscatches this. - Objects and functions as dependencies. A new object is created on every render, so the effect re-runs every time. Move it inside the effect, or wrap it with
useMemooruseCallback. - Updating state that is in the dependency array. This can create an infinite loop.
- Using an effect for things that are not side effects. Values you can compute from props or state should be calculated while rendering, not stored with an effect.
- Making the effect function async. Effects must return nothing or a cleanup function. Define an async function inside and call it.
Do you need an effect at all?
If you are responding to a click, put the code in the event handler. Use effects to synchronise with something outside React. The React documentation page "You Might Not Need an Effect" is worth reading.
The effect lifecycle in plain words
Think of each render as having its own effect. After React paints the screen, it runs the effect with the values from that render. When dependencies change, React first runs the cleanup from the previous effect, then runs the new effect. When the component unmounts, it runs the last cleanup. Thinking this way explains why stale values appear when you leave something out of the dependency array.
Why effects run twice in development
In React 18 and later, Strict Mode mounts, unmounts and mounts a component again in development to reveal missing cleanup. If your effect sets something up, the cleanup must tear it down so that a second setup works correctly. This does not happen in production builds.
Fixing stale values
A common bug: an interval keeps using an old value of state because the effect ran once with an empty dependency array. The fix is to use the functional form of the state setter, as in setCount((c) => c + 1), or to add the value to the dependency array and let the effect re-run.
// Buggy: count is always 0 inside the interval
useEffect(() => {
const id = setInterval(() => setCount(count + 1), 1000);
return () => clearInterval(id);
}, []);
// Fixed: no dependency on count
useEffect(() => {
const id = setInterval(() => setCount((c) => c + 1), 1000);
return () => clearInterval(id);
}, []);Subscribing to browser events
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);Alternatives to effects
- Derived values: compute them in the render body, for example
const total = items.reduce(...). - Event handlers: do actions caused by a click inside the click handler.
- Data fetching libraries: TanStack Query, SWR or your framework's loader handle caching, retries and race conditions better than a hand-written effect.
- useSyncExternalStore: the correct hook to subscribe to an external store.
- useLayoutEffect: only for measuring layout before the browser paints.
Debugging checklist
- Does the effect use any variable that is missing from the dependency array?
- Is a dependency a new object or function created on every render?
- Does the effect set state that is itself a dependency?
- Is there a cleanup for every timer, listener and subscription?
- Could this logic live in an event handler or be computed during render instead?
Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.
Related & Trending Stories
Recommended based on your reading interest
