# Effect Cleanup

> How to prevent memory leaks and duplicate subscriptions by returning a cleanup function from your effects.

Subject: React | Lesson 16 of 48 | 3 min read
Interactive lesson: https://codewithanimation.in/react/effect-cleanup
Previous: [Stale Closures in Hooks](https://codewithanimation.in/react/stale-closures.md) | Next: [Strict Mode](https://codewithanimation.in/react/strict-mode.md)

## What it is

When you write a `useEffect`, you can optionally return a function from it. This is called the **cleanup function**.

React will execute this cleanup function at two specific times: right before the component unmounts (is destroyed), and right before the effect re-runs due to a dependency changing.

## Why it matters

Many side effects are persistent. If you call `setInterval`, the browser will keep ticking that timer forever until you explicitly call `clearInterval`.

If a component mounts, starts a timer, and then unmounts, the timer is still running in the background! This is a memory leak. Over time, your application will become sluggish and crash.

## How to use it

Return an arrow function from your effect that undoes whatever the main body of the effect did.

```tsx
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, []);
```

## Common mistake: The duplicate subscription trap

If you omit the cleanup function on an effect that has dependencies, it's even worse than a memory leak.

If the effect runs when `userId` changes, and you subscribe to a chat room for `userId=1`, then the user switches to `userId=2`. The effect runs again and subscribes to room 2. Because you didn't clean up room 1, the user is now receiving chat messages for both rooms simultaneously!

## Tip: Symmetrical Logic

A good rule of thumb is that your cleanup function should perfectly mirror your setup logic. If setup is `subscribe()`, cleanup is `unsubscribe()`. If setup is `addEventListener()`, cleanup is `removeEventListener()`.

## Try it: The Ghost Listeners

Mount and unmount the components repeatedly. The buggy component leaves behind a 'ghost' event listener every time it unmounts! The fixed component cleans up after itself.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/effect-cleanup

## Check yourself

### Question 1

When does React execute the cleanup function returned by `useEffect`?

- A. Only when the component unmounts from the screen.
- B. Right before the component unmounts, AND right before the effect re-runs if dependencies changed.
- C. Immediately after the setup function finishes executing.

Correct answer: B

React always cleans up the previous effect before applying the new one to ensure stale data or duplicate subscriptions don't pile up.

- Why not A: It also runs before re-running the effect.
- Why not C: If it ran immediately, the effect would be undone instantly.

### Question 2

You start a `setInterval` in an effect but forget to return a cleanup function. The user navigates to a different page and the component unmounts. What happens?

- A. React automatically clears the interval because the component unmounted.
- B. The interval continues to run forever in the background.
- C. The browser detects the detached interval and stops it.

Correct answer: B

This is a classic memory leak. The timer will keep executing, potentially trying to update state on a component that no longer exists, which causes a React warning.

- Why not A: React does not track raw browser APIs. You must clean them up manually.
- Why not C: The browser has no way of knowing you don't need it anymore.

### Question 3

Which of the following is the correct syntax for a cleanup function?

- A. `useEffect(() => { ... return cleanup(); })`
- B. `useEffect(() => { ... return () => cleanup(); })`
- C. `useEffect(() => { ... }, [cleanup])`

Correct answer: B

You must return a function definition (like an arrow function) so React can call it later.

- Why not A: This executes the cleanup immediately and returns its result.
- Why not C: The cleanup function is returned, not passed in the dependency array.

## Remember this

- Effects that set up subscriptions, timers, or event listeners require cleanup.
- Return a function from your `useEffect` to act as the cleanup phase.
- Cleanup runs before the component unmounts.
- Cleanup also runs before the effect re-runs when a dependency changes.
