
Stale Closures in React: Why Your Interval Sees Old State
- كاتب موثّق
- React 19
محتويات المقال
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
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.
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
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
draft is a the Effect reads, the exhaustive-deps lint rule flags it, and the docs recommend treating that warning as a compilation error.
[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
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:
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)} />;}import { useEffect, useEffectEvent, useState } from "react";export function DraftEditor({ docId }: { docId: string }) { const [draft, setDraft] = useState(""); // Fired by the timer: reads the latest draft, never restarts it const onTick = useEffectEvent((id: string) => { saveDraft(id, draft); }); useEffect(() => { const timer = setInterval(() => onTick(docId), 30_000); return () => clearInterval(timer); }, [docId]); // typing can't reset the timer return <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />;}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
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.
setSecondsLeft((s) => s - 1) | ||
docId, roomId, delay | ||
draft, theme, isMuted | ||
onTick(docId), onVisit(url) | ||
useCallback | handleSave |
How to apply it in your project
Find the suppressions Search for eslint-disablecomments that mentionreact-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.Sort each missing value For 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. Name Effect Events after what happened React's docs suggest names like onTick,onVisit,onMessageoronConnected, things that happen from the user's point of view. Be suspicious ofonMount: it usually hides logic that should be reactive.Test with values that change Stale 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-depsis how stale closures start.Use an updater for state computed from state, a dependency for values that should restart the work, and useEffectEventfor 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.
التعليقات (0)