React useState Not Updating Immediately? State Snapshots Explained
React gives each render a snapshot of state. Calling a setter queues another render; it does not change the variable in the handler that is already running. So logging count immediately after setCount still prints the old value.
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
const nextCount = count + 1;
setCount(nextCount);
console.log(count); // 0 on the first click
console.log(nextCount); // 1 on the first click
}
function addThree() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<>
<p>Count: {count}</p>
<button onClick={handleClick}>Add one</button>
<button onClick={addThree}>Add three</button>
</>
);
}
Use a local variable like nextCount when the current handler needs the value it just calculated. Use a functional updater when the new value depends on pending state, especially when queuing several updates. In addThree, each updater receives the previous updater’s result. Calling setCount(count + 1) three times would instead queue the same replacement value three times.
An updater does not mutate the current snapshot or make the setter awaitable. Keep updater functions pure. If you need to synchronize an external system with the committed state, use an effect that depends on that state.
Try both approaches in the React coding interview examples, or read React’s guide to state as a snapshot.
Further Resources
How Long Should a Resume Be? 1–2 Pages + Examples
Choose one or two pages for your resume. Compare junior and senior developer examples, see what to cut, and use the resume-length checklist.
Read HereHow to Prepare for a Phone Interview: Checklist & Answers
Learn how to prepare for a phone interview with a 30-minute prep plan, seven sample answers, and a copyable checklist for US job seekers.
Read HereNext.js vs React: Performance and SEO Comparison
Discover the key differences between Next.js and React in terms of performance, SEO capabilities, rendering methods, and use cases. Learn which framework is best suited for your project.
Read HereGit Stash Explained: Save, Apply, Pop & View Changes
Struggling with git stash? Learn how to stash, apply, pop, and view changes with simple commands. Learn Git stash for efficient workflow!
Read HereReact 19: New Features List [Interview Ready]
Get interview-ready with our comprehensive guide on React 19, covering its groundbreaking advancements, new features, improved performance, and backward compatibility.
Read Here