الانتقال إلى المحتوى
FrontendReact· 7 دقائق للقراءة

Stale Closures in React: Why Your Interval Sees Old State

A function sees the render that created it. Pick an updater, a dependency or useEffectEvent to fix it.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

Support forwards a ticket: "Auto-save says it saved my reply every 30 seconds, but after a reload the box is empty." The editor's Effect starts an interval that calls saveDraft(docId, draft), and it really does fire every 30 seconds. It just sends an empty string each time: the value draft had when the timer started, before the user typed a single letter. Someone had silenced the linter's warning about draft, because adding it made the timer restart on every keystroke.

The common misconception

The belief: a callback reads its variables when it runs, so a function called by setInterval, setTimeout or an event listener sees the current props and state. If draft is in scope, the timer saves whatever is in the box right now.

It's a reasonable expectation, and in plain JavaScript it's often true. A closure holds on to variables, not copies of their values, so a module-level let that keeps being reassigned looks fresh to every callback that reads it. Class components felt the same way, because this.state was read at the moment the callback ran. And many of these bugs stay hidden: if a value never changes after the first render, the old one and the new one are equal, and the bug waits for the day they aren't.

What actually happens

Every render has its own variables

A function component is called once per render, and each call declares its own draft, its own docId and its own functions. As an earlier article in this path showed, state is a snapshot: setDraft doesn't reassign the draft you already have. It asks React for a new render, where a brand-new draft constant holds the new text. A function created in the first render closes over the first render's draft, and that variable never changes. The closure isn't wrong about what it captured; it captured a variable from a render that's already over. That's a .

An Effect keeps the functions it started with

An interval keeps the callback it was given until something clears it. With an Effect that never re-runs, the timer calls a function from one old render for the component's whole life. React's docs describe this exact bug: when an Effect claims it depends on nothing, React keeps using the function from the initial render. Since draft is a the Effect reads, the exhaustive-deps lint rule flags it, and the docs recommend treating that warning as a compilation error.

Obeying the linter fixes the stale value but not the product. With [docId, draft] as dependencies, every keystroke runs the cleanup, clears the interval and starts a fresh 30-second wait. Someone who types steadily never reaches a tick, so nothing is saved until they stop for half a minute. The timer shouldn't restart when the text changes. It should read the text when it fires.

Read the latest value without reacting to it

That's the job of an . useEffectEvent wraps logic that an Effect fires but that isn't part of what the Effect keeps in sync. When it's called, it runs with the latest committed props and state, and it stays out of the dependency array, so the values it reads never restart the Effect:

TSX DraftEditor.tsx
import { useEffect, useState } from "react";export function DraftEditor({ docId }: { docId: string }) {  const [draft, setDraft] = useState("");  useEffect(() => {    const timer = setInterval(() => {      saveDraft(docId, draft); // draft from the render that started it    }, 30_000);    return () => clearInterval(timer);    // eslint-disable-next-line react-hooks/exhaustive-deps  }, [docId]);  return <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />;}

The Effect now depends only on docId: open another document and React clears the old timer and starts a new one. Typing changes draft, which only onTick reads, so the timer keeps its rhythm and each tick saves the current text. Passing docId as an argument says it's part of the event, the document this timer was started for, and keeps the linter checking it as a dependency.

Not every stale value needs an Effect Event

Sometimes the callback reads state only to compute the next state, like a countdown doing setSecondsLeft(secondsLeft - 1). Pass an updater instead: setSecondsLeft((s) => s - 1). React queues the function and hands it the latest value during the next render, so the Effect doesn't read secondsLeft at all and has nothing to go stale.

The callback…FixExamples
Only computes the next state from the previous oneAn updater function, no dependencysetSecondsLeft((s) => s - 1)
Uses a value that should restart the workAdd it to the dependency arraydocId, roomId, delay
Reads a value it shouldn't react toRead it inside an Effect Eventdraft, theme, isMuted
Needs the value from when the work startedPass it as an Effect Event argumentonTick(docId), onVisit(url)
Runs on a click or is passed to a childA regular function or useCallbackhandleSave

How to apply it in your project

  1. Find the suppressionsSearch for eslint-disable comments that mention react-hooks/exhaustive-deps. Each one marks an Effect that may be reading stale values. Remove the comment and read what the linter says is missing.
  2. Sort each missing valueFor every value the linter names, ask the table's question. State used only to compute the next state becomes an updater, a value that should restart the work becomes a dependency, and a value to read without reacting moves into an Effect Event.
  3. Name Effect Events after what happenedReact's docs suggest names like onTick, onVisit, onMessage or onConnected, things that happen from the user's point of view. Be suspicious of onMount: it usually hides logic that should be reactive.
  4. Test with values that changeStale closures hide when values never change after the first render. Type while the timer runs, switch rooms quickly or toggle a setting mid-request, then check what the callback actually sent.

Key takeaways

  • A function sees the variables of the render that created it; setting state creates new variables in a new render.
  • An Effect that leaves out a value it reads keeps calling functions from an old render, so silencing exhaustive-deps is how stale closures start.
  • Use an updater for state computed from state, a dependency for values that should restart the work, and useEffectEvent for values to read without reacting.
  • Effect Events are only for logic fired from Effects: never to skip dependencies, never in handlers, props or the dependency array.

📚 المصادر

  1. Separating Events from Effects — React
  2. useEffectEvent — React API Reference
  3. Removing Effect Dependencies — React
  4. React 19.2 — React Blog

التعليقات (0)