08 / 14

What should we do in cleanup functions?

Difficulty: 5/10
useEffect cleanup, resource management, memory leaks
  1. 1

    Cancel network requests.

  2. 2

    Clear timeouts

  3. 3

    Clear intervals

  4. 4

    Remove event listeners

  5. 5

    Close WebSockets.

Scenario Questions

0-2 years experience

  1. 1You have a functional component that starts a setInterval inside useEffect. How do you make sure the interval stops when the component unmounts?
  2. 2If you add a window resize listener in a component, what do you need to do in the cleanup function to avoid issues?
  3. 3What would happen if you forget to return a cleanup function from a useEffect that opens a WebSocket connection?

2-5 years experience

  1. 1We saw a memory leak after navigating away from a page that fetches data with fetch inside useEffect. Walk me through how you'd adjust the effect to prevent the leak.
  2. 2During a code review, a teammate's useEffect creates a subscription but doesn't clean it up. How would you explain the impact and what change would you suggest?
  3. 3Our component uses an AbortController to cancel a fetch request. Where should the abort be called and why?

5-8 years experience

  1. 1Design a reusable custom hook that establishes a WebSocket connection and guarantees proper cleanup across multiple components. What edge cases do you consider?
  2. 2In a large app many components set up interval timers. How would you architect a centralized timer manager to avoid redundant timers and ensure cleanup?
  3. 3How would you test that a component's cleanup logic works correctly under rapid mount/unmount cycles?

8+ years experience

  1. 1Our legacy codebase has many class components with componentWillUnmount cleanup scattered throughout. How would you plan a migration to functional components with hooks while ensuring no resource leaks?
  2. 2When introducing a global event bus, what strategy would you adopt to enforce consistent cleanup across teams and prevent memory bloat?
  3. 3Discuss the trade‑offs of delegating cleanup responsibilities to a higher‑order component versus each component handling its own cleanup.

Follow-up Questions

  • What kinds of bugs typically surface when a cleanup is omitted?
  • How does the timing of the cleanup affect user experience or performance?
  • Can you think of a situation where you would conditionally skip a cleanup step?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.