Sub topic 6
Effects and cleanup inside a hook
This chapter assumes you know useState, the basics of useEffect, closures, and the Rules of Hooks. It covers how an effect lives inside a custom hook and why its cleanup function matters.
Why effects belong in hooks
An effect synchronizes your component with something outside React: a timer, a socket, a DOM listener. If several components need the same synchronization, put the effect in a custom hook. Callers then get the behavior without seeing the setup and teardown code.
An effect can return a cleanup function. React calls it before the effect runs again and when the component unmounts. Setup and cleanup should be mirror images: whatever the effect starts, the cleanup stops.
A hook with cleanup
useDebouncedValue returns a value that follows its input only after the input 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;
}Suppose a user types in a search box and value changes on every keystroke. Each change follows these steps:
- React re-renders and sees that
valuechanged. - React runs the previous effect's cleanup, which cancels the old timer.
- React runs the effect again, which starts a new timer.
Only the timer from the last keystroke survives long enough to fire. Without the cleanup, every keystroke would leave a timer running, and each one would eventually call setDebounced.
What belongs in the dependency array
The effect reads value and delay, so both appear in the array. When either changes, the old timer is cleared and a new one starts with the current values. Dependency rules get a full chapter later. For now, treat the array as the list of reactive values the effect reads.
Designing the hook around the effect
A few habits keep effect-based hooks predictable:
- Return only what callers need.
useDebouncedValuereturns the value and keeps the timer private. - Start and stop in the same place. If you call
addEventListenerorsetIntervalin the effect, remove or clear it in the cleanup. - Keep one concern per effect. Two unrelated side effects in one hook are easier to reason about as two effects.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| No cleanup for a timer or listener | Leaks and duplicate callbacks | Return a function that undoes the setup |
| Leaving out a value the effect reads | The effect uses stale values | List every reactive value |
| Updating state after unmount from an old callback | Wasted work and confusing behavior | Cancel the work in cleanup |
Exercise
A hook calls setInterval(tick, 1000) inside useEffect with an empty dependency array and returns nothing from the effect. What goes wrong after the component unmounts, and how do you fix it?
Show answer
The interval keeps running after unmount, so tick keeps being called and may update state or hold references that should be released. Store the id and return a cleanup function: const id = setInterval(tick, 1000); return () => clearInterval(id);.
Exercise
In useDebouncedValue, what happens if you delete delay from the dependency array and the caller changes delay from 300 to 1000 while the value stays the same?
Show answer
The effect does not re-run, so the already-scheduled timer, and any later ones, keep using the old delay of 300 from the effect's first closure. The hook ignores the new delay until value changes and the effect re-runs, and even then the effect would use whatever delay was captured at that render.