Ch. 3 · React

React Effect Cleanup and Subscription Ownership

React Effect Cleanup and Subscription Ownership. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Cleanup reverses setup when dependencies change or the component leaves the tree. Each setup should own precisely the resources its cleanup releases.

Before you start

You should know how a function component renders JSX, receives props and handles events. Follow the value through render, interaction and the next render. Small snippets below belong inside an existing React application unless they are explicitly shown as complete components.

The practical goal is to reason through this situation: A room subscription cleanup removes the listener registered by that setup. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Record resource identity

The setup owns the listener function and target it registers. Cleanup must use that same function reference.

Step 2: Mirror setup operations

Add one listener and remove that listener. Avoid removing an unrelated inline arrow function that merely looks similar.

Step 3: Test repeated lifecycles

Mount, change dependencies and unmount. Development lifecycle checks can reveal missing cleanup even before users navigate repeatedly.

Worked scenario

A room subscription cleanup removes the listener registered by that setup.

useEffect(() => {
  function onResize() { updateSize(window.innerWidth); }
  window.addEventListener('resize', onResize);
  return () => window.removeEventListener('resize', onResize);
}, []);
JSX

UpdateSize must be a stable function for this dependency list, such as a state setter; otherwise include its reactive dependency. Registration and removal share the same onResize closure.

Common mistake

Removing a different callback reference leaves the original listener attached.

Verify the behavior

Count registrations and removals, then emit after unmount. Verify no destroyed component receives the event.

Interview exercise

Verify a subscription lifecycle.

Answer and reasoning

Test mount, dependency change and unmount, checking that only the active subscription receives events.

Continue learning

Compare the scenario with the React interview questions and test your understanding with the React MCQs. For terminology and implementation details, consult the reference material.

More in React

read ✓React · hard

React Context Splitting for Performance

Stop a single context value from re-rendering every consumer by splitting state and dispatch and memoizing the provider value.

~2 min readread →
esc