I'm trying to update a counter value in React using useState,
I'm trying to update a counter value in React using useState, but when I log the state right after calling the setter, it still shows the old value. I expected the updated value to be reflected immediately.
What I've tried:
I checked that I'm calling the setter correctly and not mutating state directly, but the console.log right after setCount still prints the stale value.
Code:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count); // expected 1, but logs 0
};
return (
Count: {count}
);
}
export default Counter;
Expected behavior: After clicking the button, I expected console.log(count) to print the updated value (1).
Actual behavior: console.log(count) prints the old value (0), and the UI only updates on the next render.
Environment:
React 18.2.0
Created with Vite
Chrome 126