# Stale Closures in Hooks

> Why your hooks sometimes 'forget' the latest state, and how to fix the most notorious bug in React.

Subject: React | Lesson 15 of 48 | 5 min read
Interactive lesson: https://codewithanimation.in/react/stale-closures
Previous: [The Dependency Array](https://codewithanimation.in/react/dependency-array.md) | Next: [Effect Cleanup](https://codewithanimation.in/react/effect-cleanup.md)

## What it is

A closure is a JavaScript feature where an inner function has access to the variables of its outer function.

In React, every render creates a brand new set of variables. A 'stale closure' happens when an asynchronous callback (like a timer, an event listener, or a `useEffect`) gets trapped holding onto the variables from an *old* render instead of the current one.

## Why it matters

Stale closures are the most confusing, frustrating, and common source of bugs for React developers.

You might look at your screen and see `count = 5`, but inside your `setInterval` or `setTimeout`, if you log `count`, it says `0`! Your function is literally living in the past.

## How it happens

Imagine you write: `useEffect(() => { setInterval(() => setCount(count + 1), 1000) }, [])`.

Because the dependency array is empty `[]`, the effect only runs on the very first render, when `count` is `0`.

The interval callback captures that `0`. Every second, it runs `setCount(0 + 1)`. The screen updates to `1`. A second later, it runs `setCount(0 + 1)` again. It gets stuck at `1` forever.

## Common mistake: How to fix it

**Fix 1: The Dependency Array:** Add `count` to the dependency array. This forces the effect to recreate the interval with the new `count` every time it changes. (Note: you MUST clear the interval on cleanup, or you will spawn hundreds of intervals).

**Fix 2: Functional State Updates:** Instead of capturing the variable `count`, pass a function to the setter: `setCount(prevCount => prevCount + 1)`. The setter always receives the absolutely latest state from React, bypassing the closure entirely.

## Tip: Event Listeners

This doesn't just happen with `useEffect`. If you add a vanilla JS event listener (like `window.addEventListener`) inside a `useEffect` with an empty dependency array, its callback will also suffer from stale closures. You must use the functional updater or Refs to escape it.

## Try it: The Stuck Interval

Start the intervals. Notice how the 'Stale' counter gets permanently stuck at 1, while the 'Fixed' counter successfully counts up.

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

## Check yourself

### Question 1

What exactly is a 'stale closure' in the context of React?

- A. When a component forgets to import a necessary Hook.
- B. When a function (like a timer callback) is executed using state or prop values from a previous, outdated render.
- C. When React fails to close an HTML tag properly.

Correct answer: B

Because React re-runs the entire component function on every render, asynchronous callbacks can easily get trapped 'looking' at the variables from the specific render in which they were created.

- Why not A: That would be a ReferenceError.
- Why not C: That would be a syntax error.

### Question 2

You write `useEffect(() => { setInterval(() => setCount(count + 1), 1000) }, [])`. `count` starts at 0. What happens?

- A. The count increments by 1 every second forever.
- B. The count goes to 1, and stays at 1 forever.
- C. React crashes with a Stack Overflow.

Correct answer: B

The effect only ran once. It captured `count = 0`. Every second, it evaluates `setCount(0 + 1)`. It never sees the updated state.

- Why not A: Because it's a stale closure, it will get stuck.
- Why not C: It won't crash, it will just quietly do the wrong math forever.

### Question 3

What is the cleanest way to fix a stale closure when trying to increment a counter inside an interval?

- A. Use `setCount(prevCount => prevCount + 1)`.
- B. Remove the dependency array entirely.
- C. Force the component to remount.

Correct answer: A

By passing a callback to the setter (`prev => prev + 1`), you don't need to capture the `count` variable at all. React guarantees the callback receives the absolutely latest state.

- Why not B: This would create a new interval on every render, causing an explosion of overlapping intervals.
- Why not C: This is a terrible hack that destroys performance and user experience.

## Remember this

- A stale closure happens when a callback captures variables from an old render.
- It almost always happens in `useEffect`, `setInterval`, or event listeners.
- If you lie about your dependency array, you will get stale closures.
- Functional state updates (`setCount(c => c + 1)`) are the best weapon against stale closures.
