React Reference ยท Effect and Ref Hooks
React useEffect cleanup
Reference for the cleanup function returned from a React useEffect: when it runs, what to put in it, how it handles stale async results and StrictMode.
An effect can return a function. React calls it the cleanup, and its job is to undo whatever the setup did: clear a timer, remove an event listener, close a connection, cancel a request. Cleanup is what makes an effect safe to run many times.
React runs cleanup in two situations: before the effect runs again because a dependency changed (with the old values in its closure), and when the component is removed from the screen. It does not run after the very last render unless the component unmounts.
useEffect(() => { window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, []);
Try it
Click the button right away: user 1's slow answer arrives after user 2's, but the cleanup flag makes the component ignore it.
Syntax
useEffect(() => { // setup return function cleanup() { // undo the setup }; }, deps);
type EffectCallback = () => void | (() => void);
| Part | Description |
|---|---|
| cleanup function | Takes no arguments and returns nothing. Sees the props and state of the render whose setup created it. |
| return value | Optional. Return undefined (or nothing) when there is nothing to undo. |
Edge cases: returning anything other than a function or undefined (a promise from an async setup, for example) triggers a warning in development.
Usage notes
- Mirror the setup. Every subscribe needs an unsubscribe, every
setTimeoutaclearTimeout, everyconnect()adisconnect(). If you cannot undo it, it probably does not belong in an effect. - StrictMode check: in development React runs setup, cleanup, setup on mount to prove the pair is symmetrical. If the console shows a duplicate effect that looks wrong, the cleanup is incomplete.
- Closures: cleanup uses the values from the render that created it, which is exactly what you want when removing a listener you attached with that render's handler.
- Cancelling fetches: use
AbortControllerand callcontroller.abort()in cleanup, or a boolean flag as above. Aborting also saves bandwidth; the flag only ignores the result. - Analytics-style events that must happen once cannot be undone, so the development double run may send them twice. Send them from event handlers when possible.
- Order: on an update, all cleanups run before any new setup of that commit.
- Unmount timing: cleanup runs when a component is removed, a
keychanges (which remounts it), or a parent stops rendering it.