
State Is a Snapshot: Why setCount(count + 1) Twice Adds Only One
- كاتب موثّق
- React 19
محتويات المقال
total right after the first update, sees the old number, and decides that setTotal is asynchronous and needs an await. The await changes nothing, because the problem was never about timing.
The common misconception
setTotal(total + 120) updates total, maybe a moment later, so the next line, or at least the next tick, sees the new value.
x = x + 1 changes x on the spot, and setTotal reads like an assignment with a function call around it. Folklore adds "setState is async", which suggests that waiting would help. And there is a true part: React does process the update later, after your handler finishes. What the belief misses is that the variable in your handler never changes at all, no matter how long you wait.
What actually happens
Each render gets its own copy of state
Cart, useState hands back the current value, and const [total, setTotal] stores it in a constant that belongs to that one call of your function. Event handlers created during that render close over that constant. The docs call this a snapshot: props, handlers and local variables are all computed from the state at the time of the render, and a state variable's value never changes within a render.
A setter queues an update for the next render
setTotal(total + 120) doesn't touch total. It adds "replace with 120" to a queue for that piece of state and requests a render. React waits until all the code in the event handler has run, then processes the queue and renders once. This is , and it's why you never see a half-updated screen. The setter doesn't even return anything, so await setTotal(...) awaits undefined and gets nothing back.
Why two calls add only one
addItem calls run inside the same click handler, so both read the same snapshot:
import { useState } from "react";export function Cart() { const [total, setTotal] = useState(0); function addItem(price: number) { setTotal(total + price); // queues "replace with total + price" } function addBundle() { addItem(120); // replace with 0 + 120 addItem(80); // replace with 0 + 80, and the last one wins } return <button onClick={addBundle}>Add bundle ({total} EGP)</button>;}import { useState } from "react";export function Cart() { const [total, setTotal] = useState(0); function addItem(price: number) { setTotal((t) => t + price); // queues "add price to the latest value" } function addBundle() { addItem(120); // 0 → 120 addItem(80); // 120 → 200 } return <button onClick={addBundle}>Add bundle ({total} EGP)</button>;}total is 0 in this render, so the queue holds "replace with 120" and then "replace with 80". React applies them in order and the last replacement wins. In the second, each call queues an . During the next render, React feeds the result of each updater into the next one, so the chain runs 0, 120, 200. Plain values and updaters can be mixed in one queue, and React applies them strictly in order:
setCount(count + 1) twice | ||
setCount((c) => c + 1) twice | ||
setCount(count + 5), then setCount((c) => c + 1) | ||
setCount((c) => c + 1), then setCount(42) |
Waiting doesn't refresh the snapshot
import { useState } from "react";export function NewsletterForm() { const [email, setEmail] = useState(""); async function handleSubscribe() { const cleaned = email.trim(); // compute the next value once setEmail(cleaned); // the input shows it on the next render await subscribe(cleaned); // send the local value console.log(email); // still the untrimmed snapshot, even after await } return ( <> <input value={email} onChange={(e) => setEmail(e.target.value)} /> <button onClick={handleSubscribe}>Subscribe</button> </> );}subscribe(email) after setEmail(email.trim()), it would have sent the untrimmed address. handleSubscribe belongs to the render where email had the trailing space, and that render's constant never changes, before the await or after it. The fix the docs recommend is the one above: compute the next value into a local variable, then pass that same variable to the setter and to everything else that needs it.
How to apply it in your project
Look for a setter followed by a read Search your handlers for setX(...)followed by a use ofx. Compute the next value in a local constant and use it in both places.Use updaters for repeated or shared updates When one event updates the same state twice, or a helper like addItemsets state, writesetX((x) => ...)so each update builds on the queued value.Stop waiting for state Remove awaitbefore setters andsetTimeoutcalls meant to "let state settle". Neither refreshes the snapshot; the local value from step one does the job.Merge state that changes together If the next value of one state variable depends on another one, combine them into one object or move the logic into useReducer, so a single update sees both.
Key takeaways
Inside one render, a state variable is a constant snapshot; setters never change it. A setter queues an update and requests a render; React processes the queue after the handler finishes. Two setCount(count + 1)calls queue the same replacement;setCount((c) => c + 1)builds on the queued value.Need the new value right away? Compute it in a local variable and use that; waiting never refreshes the snapshot.
التعليقات (0)