Questions
Why does this component log the old state value after calling a useState setter?
How Different Experience Levels Approach This
The console.log should show the new value since we just updated it with setCount.
State updates in React are asynchronous. When you call setCount, React schedules an update—it doesn't happen immediately. The count variable still holds the value from the current render, so the console.log shows the old value.
To log the new value, you need to use useEffect with the state variable in its dependency array. This runs after the re-render when the new value is available.
Key insight: The functional update form setCount(c => c + 1) prevents bugs from batched updates, but doesn’t solve this logging issue—you still need useEffect to react to state changes.
- Context over facts: Explains when and why, not just what
- Real examples: Provides specific use cases from production experience
- Trade-offs: Acknowledges pros, cons, and decision factors
import React, { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
// Increment the state
setCount(count + 1);
// THE BUG: Try to log the new state value immediately
console.log(`The new count is: ${count}`);
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>Increment</button>
<p>Check the console after clicking the button.</p>
</div>
);
} The Solution
import React, { useState, useEffect } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
// FIX: This effect runs *after* the re-render with the new count
useEffect(() => {
if (count > 0) {
console.log(`The new count is: ${count}`);
}
}, [count]); // The dependency array is key!
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
}
Practice Question
Why shouldn't you rely on a state variable's new value immediately after calling its useState setter function in the same block of code?