React State Behavior in Interviews: Understanding State Updates

The React state behavior question I faced in an interview recently 🧠 I was given a simple counter component and asked to predict the output. const Increment = () => { let [state, setstate] = useState(0) let handleIncrement = () => { setstate(state + 1) setstate(state + 1) setstate(state + 1) console.log(state) } return ( <div> <h1>{state}</h1> <button onClick={handleIncrement}>Increment</button> </div> ) } When clicking the button: • UI output became 1 • Console output was 0 At first glance, it looks like the state should increment 3 times. But it didn’t. The reason? React doesn’t update state immediately. It batches state updates for performance and all three updates used the same previous state value. The Fix: Using functional updates: setstate(prev => prev + 1) setstate(prev => prev + 1) setstate(prev => prev + 1) Now the state increments correctly. The Lesson: React is not just about components and hooks — understanding how state updates and re-renders work is very important, especially for interviews and real-world performance. #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #SoftwareDeveloper #Programming #Coding #Tech #SoftwareEngineering #FrontendDeveloper #ReactDeveloper #CodingInterview #DeveloperJourney #OpenToWork #JobSearch

To view or add a comment, sign in

Explore content categories