MyInternships.in

React Hooks

React useEffect Cleanup Function

Returning a function from useEffect gives React a cleanup routine. It runs before the effect executes again and once more when the component unmounts, which is where you cancel timers, remove listeners, close sockets and abort requests.


What is useEffect Cleanup Function in React?

Returning a function from useEffect gives React a cleanup routine. It runs before the effect executes again and once more when the component unmounts, which is where you cancel timers, remove listeners, close sockets and abort requests.

Why useEffect Cleanup Function matters

Without cleanup, a component that mounts and unmounts repeatedly leaks a timer or listener each time. The symptoms — memory growth, duplicate network calls, "cannot update state on an unmounted component" — all trace back to a missing cleanup.

useEffect Cleanup Function example

Three effects that must clean up
JSX
// interval
useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);

// event listener
useEffect(() => {
  const onResize = () => setWidth(window.innerWidth);
  window.addEventListener('resize', onResize);
  return () => window.removeEventListener('resize', onResize);
}, []);

// subscription
useEffect(() => {
  const sub = socket.subscribe(roomId, onMessage);
  return () => sub.unsubscribe();
}, [roomId]);

How this works

Each cleanup undoes exactly what its effect set up. Note the listener uses the same function reference for add and remove — an inline arrow in removeEventListener would remove nothing.

Key points to remember

  • Cleanup runs before every re-run, not only on unmount.
  • It receives no arguments — capture what you need in the effect’s closure.
  • StrictMode deliberately exercises cleanup in development so missing ones surface early.

Common mistakes with useEffect Cleanup Function

  • Passing a different function reference to removeEventListener than to addEventListener.
  • Returning a promise from the effect (an async effect function) — the return value must be a cleanup function or nothing.
💡

Write the cleanup at the same moment you write the setup. Going back to add it later is how leaks get shipped.

React useEffect Cleanup Function— Interview Questions & FAQs

Can useEffect be async?+

Not directly — an async function returns a promise and React expects a cleanup function. Declare an async function inside the effect and call it, then return a synchronous cleanup.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships