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

State Is a Snapshot: Why setCount(count + 1) Twice Adds Only One

A setter doesn't change the variable you're holding. It queues an update for the next render.

ReadIn

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

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

A bug report from the shop team: the "Add bundle" button should add a 120 EGP charger and an 80 EGP cable, but the cart total grows by only 80. Adding either item on its own works fine. The developer logs 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

The belief: calling setTotal(total + 120) updates total, maybe a moment later, so the next line, or at least the next tick, sees the new value.

It's what every other line of JavaScript has taught us. 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

React keeps state outside your component. When it renders 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

Here is the cart. Both addItem calls run inside the same click handler, so both read the same snapshot:

TSX Cart.tsx
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>;}

In the first version, 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:

What the handler calls (starting at 0)What React queuesNext render
setCount(count + 1) twicereplace with 1, replace with 11
setCount((c) => c + 1) twiceadd 1, add 12
setCount(count + 5), then setCount((c) => c + 1)replace with 5, add 16
setCount((c) => c + 1), then setCount(42)add 1, replace with 4242

Waiting doesn't refresh the snapshot

The other face of the same rule: the line after a setter still sees the old value, and so does code that runs a second later. Say a newsletter form trims the email before sending it:

TSX NewsletterForm.tsx
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>    </>  );}

Had the handler called 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

  1. Look for a setter followed by a readSearch your handlers for setX(...) followed by a use of x. Compute the next value in a local constant and use it in both places.
  2. Use updaters for repeated or shared updatesWhen one event updates the same state twice, or a helper like addItem sets state, write setX((x) => ...) so each update builds on the queued value.
  3. Stop waiting for stateRemove await before setters and setTimeout calls meant to "let state settle". Neither refreshes the snapshot; the local value from step one does the job.
  4. Merge state that changes togetherIf 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.

📚 المصادر

  1. State as a Snapshot — React
  2. Queueing a Series of State Updates — React
  3. useState — React API Reference
  4. React v18.0: Automatic Batching — React Blog

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