React State Updates: Batching and Functional Updates Explained

How I Understood React State Updates One day I wrote this small React code: import { useState } from "react"; export default function App() { const [count, setCount] = useState(0);   const handleClick = () => {    setCount(count + 1);    setCount(count + 1);    setCount(count + 1);    console.log(count);   };   console.log(count);   return (    <div>     <h1>{count}</h1>     <button onClick={handleClick}>Increment</button>    </div>   ); } And I thought something very simple would happen. I clicked the button and expected: 0 → 3 Because I increased the count three times. But React surprised me. The value became: 0 → 1 And I asked myself: 👉 Why didn't it increase to 3? So I stopped thinking like a JavaScript developer… and started thinking like React. What React actually sees React batches state updates. All three lines read the same old value. setCount(count + 1); setCount(count + 1); setCount(count + 1); • For React, this becomes: setCount(1) setCount(1) setCount(1) • So the final result is simply: 1 Not 3. • The correct way When the new state depends on the previous state, React gives us a better pattern: setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); Now React updates step by step. Result: 0 → 3 The lesson I learned State updates in React are not immediate. React schedules them and processes them together. So whenever state depends on the previous value, I now ask myself: 👉 Should I use the functional update? Small detail. Big difference. Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useState #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook

  • text

This is one of those concepts that feels tricky when you first encounter it. But the more you practice and apply it in real examples, the clearer it becomes. Thanks for sharing!

To view or add a comment, sign in

Explore content categories