Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Why does my React state update not reflect immediately after setState?

clock icon

asked 1 month ago

message icon

1

eye icon

1.3K

I have a counter and I log right after calling the setter:

1const [count, setCount] = useState(0)
2
3const handleClick = () => {
4 setCount(count + 1)
5 console.log(count) // still the old value
6}
1const [count, setCount] = useState(0)
2
3const handleClick = () => {
4 setCount(count + 1)
5 console.log(count) // still the old value
6}

The UI updates correctly, but the log is always one behind. Am I misusing the hook?

1 Answer

You are not misusing it — count is a const binding captured by that render's closure. Calling the setter schedules a re-render; it does not reassign the existing variable.

The next render creates a new count binding with the new value. Your log belongs to the old render, so it prints the old value forever.

If the next value depends on the previous one, use the updater form:

1setCount((prev) => prev + 1)
1setCount((prev) => prev + 1)

And if you need to react to the committed value, use an effect:

1useEffect(() => {
2 console.log(count)
3}, [count])
1useEffect(() => {
2 console.log(count)
3}, [count])

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions