Sub topic 6
Effects and cleanup inside a hook
This chapter assumes you know useState and useEffect basics, closures, and the Rules of Hooks from earlier chapters. It covers how effects behave inside a custom hook, why cleanup matters, and the errors people hit most often.
Why effects belong in hooks
A component renders to describe the UI. An effect is code that synchronizes the component with something outside React: a timer, a network connection, a DOM listener, a document title. React cannot manage those things for you. If you start one, you must stop it.
When you put an effect inside a custom hook, the start and stop logic lives in one named place. Every component that calls the hook gets the correct setup and teardown without repeating it.
The effect lifecycle
An effect has three parts:
- The setup function you pass to
useEffect. React runs it after the component renders and the screen updates. - An optional cleanup function that setup returns. React runs it before the next setup and when the component unmounts.
- The dependency array. React compares it with the previous render's array to decide whether to run cleanup and setup again.
The order matters. When a dependency changes, React runs the old cleanup first, then the new setup. The old cleanup still sees the values from the render that created it, because it is a closure.
A hook with a timer
useDebouncedValue returns a copy of a value that updates only after the value has stopped changing for delay milliseconds.
import { useState, useEffect } from 'react';
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}Walk through typing "re" into a search box:
- The user types "r".
valueis "r". Setup starts a timer for that value. - The user types "e" before the timer fires.
valueis now "re". React runs cleanup, which cancels the "r" timer. Setup starts a new timer. - The user stops. The timer fires and
debouncedbecomes "re".
Without the cleanup, the "r" timer would also fire. You would get extra state updates, and a slow earlier timer could overwrite a newer value. Cleanup is what makes the hook behave as "wait for quiet".
What cleanup must undo
Cleanup should reverse whatever setup started. Match each kind of setup with its reverse:
| Setup | Cleanup |
|---|---|
| `setTimeout` | `clearTimeout` |
| `setInterval` | `clearInterval` |
| `addEventListener` | `removeEventListener` with the same function reference |
| Opening a WebSocket | `socket.close()` |
| Starting a `fetch` | `controller.abort()` |
| Subscribing to a store | Calling the unsubscribe function |
The removeEventListener row has a common trap. The function you remove must be the same object you added. This does not work:
useEffect(() => {
window.addEventListener('resize', () => console.log('resized'));
return () => {
// A different arrow function, so nothing is removed.
window.removeEventListener('resize', () => console.log('resized'));
};
}, []);Give the listener a name inside the effect and use that name in both places:
import { useEffect } from 'react';
export function useWindowResizeLogger() {
useEffect(() => {
const onResize = () => console.log('resized');
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
}Stale results from asynchronous work
Timers are easy to cancel. Network requests are harder, because a response can arrive after the component no longer cares about it. Suppose url changes from /a to /b. If the /a response arrives last, it would overwrite the /b data. Cleanup solves this in two ways, and the hook below uses both.
import { useState, useEffect } from 'react';
export function useFetchJson(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => {
if (!ignore) setState({ status: 'success', data, error: null });
})
.catch((error) => {
if (!ignore && error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}Each run of the effect creates its own ignore variable and its own AbortController. Cleanup for the /a run sets that run's ignore to true, so even if its promise resolves later, the .then handler skips setState. Aborting also tells the browser to stop the request and saves bandwidth. The AbortError check keeps a deliberate cancel from showing up as a user-facing error.
The ignore flag is the more important of the two. Not every promise source supports abort, and an aborted request can still race with a response that was already in flight. The flag guarantees stale data is never written.
Effects that never need cleanup
Not every effect returns a function. Setting the document title is a one-way write with nothing to stop:
import { useEffect } from 'react';
export function useDocumentTitle(title) {
useEffect(() => {
document.title = title;
}, [title]);
}Return a cleanup only when setup leaves something running or registered. If you want the old title back on unmount, that is a design choice, so add a cleanup that restores it.
Development double-invocation
In development, React's Strict Mode runs every effect's setup, then its cleanup, then setup again, right after mounting. This is deliberate. It simulates a component unmounting and remounting, and it exposes missing cleanup.
If your hook works correctly after this setup, cleanup, setup sequence, it is safe for real remounts. If you see two timers, two listeners, or two network connections, your cleanup does not fully reverse your setup. Fix the cleanup. Do not remove Strict Mode or add a "did it already run" flag to hide the problem.
Common mistakes
- Forgetting cleanup. Intervals and listeners pile up and keep calling
setStateon components that no longer exist. - Returning a non-function.
useEffect(async () => {...})returns a promise, and React warns because cleanup must be a function or nothing. Define anasyncfunction inside the effect and call it, or use promise chains as shown above. - Cleanup that captures the wrong thing. Cleanup sees the values of the render that created it. If it needs a mutable object created during setup, such as a
controlleror an intervalid, declare that object inside the effect, as the hooks above do. - Setting state synchronously at the top of an effect on every run. The
setState({ status: 'loading', ... })call inuseFetchJsonis intentional, because it resets state whenurlchanges. Make sure any such reset is needed and cannot loop. It is safe here because it depends only onurl. - Running effects for work that belongs in an event handler. If something happens because the user clicked, do it in the click handler. Use an effect only when something must stay synchronized with a value.
Effect or event handler?
Ask what causes the work. If rendering with certain values should keep an external system in sync (a subscription for the current url, a timer for the current delay), use an effect. If a specific user action causes it (submitting a form, pressing save), use an event handler. Hooks that expose functions such as save() or refresh() let the component call them from handlers, which keeps effects focused on synchronization.
Exercise
A hook starts setInterval(tick, 1000) inside useEffect with an empty dependency array and returns nothing. In development with Strict Mode, the counter advances twice as fast as expected. What is wrong, and what is the fix?
Show answer
Strict Mode runs setup, cleanup, and setup again after mount. Because the effect has no cleanup, the first interval is never stopped, so two intervals run at once. Store the id and return a cleanup: const id = setInterval(tick, 1000); return () => clearInterval(id);. This also stops the interval on real unmounts.
Exercise
In useFetchJson, url changes from /a to /b while the /a request is still pending. What happens to the /a response if it arrives after the /b response, and which two lines of the cleanup function prevent a wrong result?
Show answer
The cleanup for the /a run has already executed. ignore = true makes the /a run's .then and .catch handlers skip setState, so the /b data stays on screen. controller.abort() also cancels the /a request in the browser, which usually means the /a response never arrives at all.