09 / 14

What are the advantages of cleaning up after an effect?

  1. 1

    saves applications from unwanted behaviours like memory leaks

  2. 2

    To avoid race conditions in async requests.

  3. 3

    To manage subscriptions in your application

Difficulty: 5/10
Topics: resource management, memory leaks, event subscriptions

Scenario Questions

0-2 years experience
  1. 1

    You added a window resize listener inside a useEffect. What steps do you take to make sure it doesn't keep firing after the component unmounts?

  2. 2

    If you set a setInterval inside an effect but forget to return a cleanup function, what symptom might you notice when navigating away from the page?

2-5 years experience
  1. 1

    Our component opens a WebSocket connection in useEffect and started receiving duplicate messages after users navigate between routes. How would you debug and fix the issue?

  2. 2

    During a performance audit you see memory usage climbing each time a modal opens. The modal adds a CSS class to document.body in an effect. Explain why a cleanup is needed and how you'd implement it.

5-8 years experience
  1. 1

    The dashboard renders dozens of charts, each attaching a ResizeObserver in useEffect. At scale we see jitter and occasional crashes. How would you redesign the cleanup strategy to be safe and performant?

  2. 2

    A legacy codebase has many effects without cleanup, leading to stale closures and memory leaks. Describe a systematic approach to refactor these across the repo, considering testing and rollout.

8+ years experience
  1. 1

    We're migrating from class components with componentWillUnmount to functional components using useEffect. What architectural guidelines would you establish for cleanup to avoid regressions across multiple teams?

  2. 2

    We plan to introduce a global event bus that many components subscribe to via useEffect. How would you design the subscription API and cleanup conventions to ensure reliability and ease of maintenance at scale?

Follow-up Questions

  • How would you verify that your cleanup logic actually runs in a test?
  • What problems arise if the cleanup closes over stale state or props?
  • When an effect runs frequently due to changing dependencies, how do you balance cleanup cost versus correctness?