React is Simple!

Think React state is easy? One wrong move and your counter breaks.

Why It Happens

React batches state updates.
Using setState(state + 1) can overwrite updates with stale values.
The functional form setState(prev => prev + 1) ensures correctness.

Don't

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

setCount(count + 1);
setCount(count + 1); 
// ❌ Result: count = 1

Do

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

setCount(prev => prev + 1);
setCount(prev => prev + 1);
// ✅ Result: count = 2

Explanation

  • setCount(count + 1) → uses an old snapshot of state.
  • setCount(prev => prev + 1) → React passes the freshest value.

Updating state without prev is like asking for “one more slice” 🍕…
but the box already got emptied. Always ask from the current box.

3

❤️

3 people reacted.

Uncertified Quasi-pseudo dev

Hi, I'm who's behind Fedify, Hollo, BotKit, and this website, Hackers' Pub! My main account is at @hongminhee洪 民憙 (Hong Minhee).

Fedify, Hollo, BotKit, 그리고 보고 계신 이 사이트 Hackers' Pub을 만들고 있습니다. 제 메인 계정은: @hongminhee洪 民憙 (Hong Minhee).

FedifyHolloBotKit、そしてこのサイト、Hackers' Pubを作っています。私のメインアカウントは「@hongminhee洪 民憙 (Hong Minhee)」に。