What You'll Learn
- 1Frame an effect as synchronization with an external system rather than as lifecycle glue
- 2Read a dependency array as a contract and predict when setup will re-run
- 3Write cleanup that cancels work instead of patching results after the fact
- 4Identify code that should move out of effects entirely
Effects synchronize with systems outside React
React components are pure functions of their props and state, and the browser is not. Subscribing to a socket, fetching from a server, setting a page title, registering a document listener, and starting an animation frame are all acts of synchronizing React's virtual world with something that lives outside it. An effect is the official channel for that synchronization, and the component's render is what tells the effect what the current configuration should be.
Framing matters because it answers the two questions that generate most bug reports. The first is when an effect should re-run: whenever the configuration it depends on changes, which is exactly what the dependency array declares. The second is what cleanup means: the effect that ran must be undone before the next one runs and before the component goes away, so that at most one subscription, one request, or one timer is live at any moment.
The dependency array as a contract
React compares the array entries with Object.is after every commit. If any entry differs, the previous effect is cleaned up and the new one runs. An empty array means the configuration never changes, so setup happens once. No array at all means the configuration changes on every render, which is rarely what you want and almost never free.
| Dependency situation | When setup re-runs | Appropriate use |
|---|---|---|
| Empty array | Once on mount | Registering a listener that never depends on props |
| Props and state the effect reads | When any of them changes | Fetching for a route param, syncing an input |
| A value recreated inline each render | On every render | Almost always a bug; stabilise the value instead |
| A setter from useState | Never changes | Safe to omit from the array in practice |
| A function passed as a prop | Every render unless the parent stabilised it | Wrap the prop in useCallback, or ref it |
| A ref object | Never changes | Correct for reading mutable values inside the effect |
The rule of listing everything you read is not arbitrary bookkeeping. Each entry is a statement about what the effect is synchronized with, and omitting one is how a component ends up fetching user seven while displaying user eight.
Cleanup that cancels, not patches
A cleanup function's job is to stop work that is no longer relevant. Returning a flag that tells the callback to ignore its result works, but it leaves the request, the timer, or the subscription running and wasting resources. Cancelling is better because the work stops.
function useDocumentTitle(title, subtitle) {
useEffect(() => {
const previous = document.title;
document.title = subtitle ? `${title} ยท ${subtitle}` : title;
return () => {
document.title = previous;
};
}, [title, subtitle]);
}
function useKeydown(key, handler) {
const saved = useRef(handler);
useEffect(() => {
saved.current = handler;
});
useEffect(() => {
const onKeyDown = (event) => {
if (event.key === key) saved.current(event);
};
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}, [key]);
}
The title hook restores the previous value, which is the honest form of undo. The keydown hook stores the latest handler in a ref so the listener is registered once per key while still calling the most recent callback, avoiding the subscription churn that comes from re-registering on every parent render.
The classic stale fetch, and its three fixes
The fetch bug has a shape you will recognise: the effect reads a prop, the prop changes quickly, and two requests are in flight at once. The slower one resolves last and overwrites the correct data.
function SearchResults({ query }) {
const [results, setResults] = useState([]);
const [status, setStatus] = useState('idle');
useEffect(() => {
if (!query) {
setResults([]);
return undefined;
}
const controller = new AbortController();
setStatus('loading');
fetch('/api/search?q=' + encodeURIComponent(query), { signal: controller.signal })
.then((res) => res.json())
.then((data) => {
setResults(data.hits);
setStatus('ready');
})
.catch((err) => {
if (err.name !== 'AbortError') setStatus('error');
});
return () => controller.abort();
}, [query]);
return (
<section>
<p>Status: {status}</p>
<ul>
{results.map((hit) => (
<li key={hit.id}>{hit.title}</li>
))}
</ul>
</section>
);
}
The three standard repairs are all valid. Abort in cleanup, as above, which stops the network work. Ignore late results by checking a token, which is useful when aborting is impossible. Or key the component on the query so the whole subtree remounts and state resets, which is the simplest option when the data is genuinely per-route. Choose one and apply it consistently; mixing approaches across a codebase is how the bug returns.
What does not belong in an effect
Effects are for synchronizing with external systems, and a surprising amount of everyday code is not that. Deriving a filtered array from a list and a query string belongs in the render, or behind useMemo if it is genuinely expensive. Responding to a user click by updating state belongs in the handler. Adjusting state when props change belongs either in the render with a state-during-render pattern, or in the effect if the change must be deferred.
The tell is a two-step render: the effect sets state, which triggers another render, which produces the output you actually wanted. If you can move the first step into the event handler or into a derived value, you remove a render and a class of race conditions at the same time. Data fetching is the exception that proves the rule, because the network genuinely is an external system with its own timing.
Deciding between an effect and an event
Most of the confusion about effects disappears once you separate two questions: did the user ask for this, or did the data change? If the user asked, the code belongs in the event handler. Clicking refresh, submitting a form, or pressing play are all intents, and the handler should update state directly without routing through an effect that watches the click.
If the data changed, the question becomes whether anything outside React needs to know. A prop that selects a document title does, so an effect that writes to the document is correct. A derived count does not, so a derivation is correct. When both questions have a positive answer, write the effect and note the external system in a comment, because that comment is the thing a future reader will need six months from now when they are deciding whether the effect can be removed.
StrictMode and the double invocation
In development, React runs effects twice, mounting, cleaning up, and mounting again, specifically so that missing cleanup becomes visible immediately. You will see two requests in the network tab and two log lines for what should be a single setup. That is not a bug in your code or in the framework; it is a test the framework runs on every effect for free.
Production runs the effect once. If your cleanup is correct, the double invocation changes nothing except the development logs. If it is missing, you will see a leaked listener, a doubled subscription, or a request that cannot be cancelled, and you will see it in development, where it is cheap to fix, rather than in production, where it is expensive.
Common Mistakes
Omitting a dependency so the effect reads a value frozen at an earlier render
Fix: List every value the effect reads, or restructure so the value is not needed inside
Setting a flag to ignore stale results while the request keeps running
Fix: Abort the request in cleanup so the work actually stops
Doing derivations inside effects and storing the result in state
Fix: Compute the derived value during render, or memoise it if it is expensive
Treating the development double mount as a bug and disabling StrictMode
Fix: Fix the missing cleanup; the double run is a free correctness test
Best Practices
- Name the system each effect synchronizes with; if you cannot, it probably is not an effect
- Return cleanup for every subscription, timer, observer, and request you create
- Keep the dependency array honest and let the linter write it for you
- Prefer one cancellation mechanism per effect rather than a mixture of flags
- Re-register listeners only when their identity or their key genuinely changes
Key Takeaways
- Effects synchronize React state with external systems, and nothing else
- The dependency array declares what the effect is synchronized with, and React re-runs setup when it changes
- Cleanup should cancel work, not merely ignore its eventual result
- Derivations, event responses, and most state updates do not belong in effects
- StrictMode's second mount is a free audit of your cleanup path