Join waitlist
ReactCommunity question

React state shows old value right after setState

Asked by Kavya Nair 2 months ago 3 answers 9 votes

const [count, setCount] = useState(0);

function handleClick() {
  setCount(count + 1);
  console.log(count); // prints old value
}

why? I literally just set it

3 answers

Tanvi Kulkarni2 months agoMost voted9

setCount doesn't change the `count` variable you have, it asks React to re-render with a new value. Your handleClick is still running with the `count` from the current render, so it logs the old one. The new value shows up in the next render.

If you need the new value right away just compute it:
const next = count + 1;
setCount(next);
console.log(next);
Sneha Reddy1 month ago4

related: calling setCount(count + 1) twice in the same handler only adds 1. use setCount(c => c + 1) if you need that

Kavya Nair1 month ago

ohh ok. thank you both

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.