React setState prev => function explained

Why setState(prev => …) Exists (And When You MUST Use It) ⚛️ Ever written this and expected +2? setCount(count + 1); setCount(count + 1); But React gave you +1 😵💫 React isn’t broken. Your mental model is. What’s actually happening 👇 Remember this rule: Each render sees its own snapshot of state 📸 In that render: count has one fixed value Both updates read from the same snapshot So React sees: setCount(0 + 1); setCount(0 + 1); ➡️ Result: 1, not 2 Why the functional updater exists 🧠 Now look at this: setCount(prev => prev + 1); setCount(prev => prev + 1); This time, React does this internally: First update → prev = 0 → 1 Second update → prev = 1 → 2 Why? Because the updater function: Runs after React processes the queue Always receives the latest state, not a stale snapshot When you MUST use prev => … ✅ Use the functional updater whenever: The next state depends on the previous state You’re doing multiple updates in a row Updates happen inside async code (setTimeout, promises, events) 💡 The real takeaway setState(value) says: “Set state to this value” setState(prev => next) says: “Calculate the next state from the latest reality” If React state feels confusing, it’s usually because you’re thinking in variables — not renders. 💬 Question for you: When did this bug first bite you? #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #SoftwareEngineering #CodingBlockHisar

  • text

To view or add a comment, sign in

Explore content categories