ReactEasy
What is cleanup in hooks?
Cleanup is the function returned from useEffect, useLayoutEffect or useInsertionEffect (and, in React 19, from callback refs) that undoes what the setup did. React calls it before re-running the effect with new values and when the component unmounts, which prevents leaks, duplicate subscriptions and updates from stale async work.
What needs cleanup
| Setup | Cleanup |
|---|---|
addEventListener | removeEventListener |
setInterval / setTimeout | clearInterval / clearTimeout |
fetch | AbortController.abort() or an ignore flag |
| WebSocket / EventSource | .close() |
IntersectionObserver / ResizeObserver | .disconnect() |
| Third-party widget init | its destroy() |
| Store subscription | the returned unsubscribe |
Animation (requestAnimationFrame) | cancelAnimationFrame |
When it runs
- Before the next setup when dependencies change (with the old values).
- On unmount.
- When an
<Activity>boundary becomes hidden (React 19.2). - In development Strict Mode, once immediately after the first mount to verify symmetry.
Ref cleanup (React 19)
<div ref={(node) => { const ro = new ResizeObserver(cb); ro.observe(node); return () => ro.disconnect(); }} />. Previously React called the ref with null.
A good test
If an effect is set up, cleaned up and set up again (as Strict Mode does), the user should not notice anything.
Code example
tsx
1import { useEffect, useState } from "react";23export function LiveCursor({ roomId }: { roomId: string }) {4 const [pos, setPos] = useState({ x: 0, y: 0 });56 useEffect(() => {7 const ws = new WebSocket(`wss://cursors.example.com/${roomId}`);8 let frame = 0;910 const onMove = (e: PointerEvent) => {11 cancelAnimationFrame(frame);12 frame = requestAnimationFrame(() => {13 setPos({ x: e.clientX, y: e.clientY });14 if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ x: e.clientX, y: e.clientY }));15 });16 };17 window.addEventListener("pointermove", onMove);1819 return () => {20 window.removeEventListener("pointermove", onMove);21 cancelAnimationFrame(frame);22 ws.close();23 };24 }, [roomId]);2526 // React 19 ref cleanup27 const observe = (node: HTMLDivElement) => {28 const ro = new ResizeObserver(() => console.log("resized"));29 ro.observe(node);30 return () => ro.disconnect();31 };3233 return <div ref={observe}>Cursor at {pos.x}, {pos.y}</div>;34}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.