ForgeFrontend — Prepare, Practice, Crack
Secure checkout
Lifetime access
Instant Drive delivery
Free updates forever

Prepare · Practice · Crack

What is the cleanup function in useEffect and when does it run?

Quick answer

The function you return from an effect; React runs it before the effect re-runs and on unmount, to tear down subscriptions, timers, and listeners.

In detail

Anything an effect sets up that persists must be cleaned up to avoid leaks and duplicate work. The cleanup runs before each re-run of the effect (with the previous deps) and once when the component unmounts. Forgetting it causes leaks like multiple intervals stacking up or listeners firing after unmount.

useEffect(() => {
  const onResize = () => setW(window.innerWidth);
  window.addEventListener("resize", onResize);
  return () => window.removeEventListener("resize", onResize);
}, []);

Why interviewers ask this: Tests whether you write leak-free effects.

This is 1 of 118+ questions in the React Interview Kit

Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.

⚡ Get the React Interview Kit → ₹399

Full kit

React Interview Kit · ₹399

Get it →