Cleanup Function Effect Cleanup
Last updated: 2026-11-02
Cleanup Function Effect Cleanup
The cleanup function is the teardown returned by an effect: it runs once before the next run of that effect and once more when the component unmounts, and it is what cancels timers, unsubscribes listeners and aborts in-flight requests. Without a cleanup, the side effect keeps running after the component is gone and leaks. The rule of thumb is simple: anything you start inside an effect and do not finish synchronously needs a matching cleanup.
| Group | Effects & Performance |
|---|---|
| Kind | Pattern |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
useEffect(() => {
const id = setInterval(tick, 1000)
window.addEventListener('resize', onResize)
return () => { // teardown: clear the old one before running the new one
clearInterval(id)
window.removeEventListener('resize', onResize)
}
}, [])
Returns:No return value; this entry describes an encoding pattern rather than a function.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
The timer adds one second every second; clicking "Pause" stops it immediately (the cleanup function runs), clicking "Resume" starts it again, and at any moment only one timer is alive.