State Updates
State Updates
Updating state in React using the setter function from useState behaves differently than simply reassigning a variable in vanilla JavaScript. There are several crucial concepts to understand about how React processes state updates.
State is a Snapshot
When React calls your component function to render the UI, the state variables for that render are snapshots of the state at that specific moment in time.
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
// What is the result after one click?
If you click the button once, you might expect the count to increase by 3. However, it only increases by 1.
Why? Because during that specific render, the count variable is 0.
The handleClick function essentially executes this:
setCount(0 + 1);
setCount(0 + 1);
setCount(0 + 1);
React queues three requests to set the state to 1. When the next render happens, the count is indeed 1.
State Updates are Asynchronous (Queued)
State updates do not happen instantly. Calling a setState function only requests an update. React queues the update and schedules a re-render.
const [name, setName] = useState('Alice');
function handleNameChange() {
setName('Bob');
console.log(name); // What does this print?
}
The console.log will print 'Alice', not 'Bob'. The name variable is a constant for the duration of that render. The value of name will only be 'Bob' on the next render, after React has processed the queued update.
Mutating Objects in State
State should always be treated as immutable. While you technically can mutate an object or array in state directly, doing so will bypass React’s reconciliation engine. Because the object reference hasn’t changed, React doesn’t realize the state has changed, and it will not trigger a re-render.
const [user, setUser] = useState({ name: 'John', age: 30 });
// ❌ WRONG: Mutating state directly
user.age = 31;
setUser(user); // React won't re-render because the object reference is the same!
// ✅ CORRECT: Create a new object reference
setUser({ ...user, age: 31 });
Interview Questions
Q: Are state updates in React synchronous or asynchronous?
A: State updates are strictly asynchronous. Calling a state setter function does not immediately mutate the state variable on the next line of code. Instead, it queues a request for React to schedule a re-render, where the new value will finally become available in the next render pass.