Menu

Why setCount(count + 1) Three Times Only Adds 1 (React Stale State)
πŸ“°

Why setCount(count + 1) Three Times Only Adds 1 (React Stale State)

DEV Community: reactΒ·Muiduzzaman LipuΒ·12 days ago
#ShtSkAz9
#devtoreact#devto#dev#count#setcount
Long article (758 words) β€” no AI summary yet.
Reading 0:00
15s threshold

This click handler calls setCount(count + 1) three times:

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

function handleClick ( ) { setCount ( count + 1 ) ; setCount ( count + 1 ) ; setCount ( count + 1 ) ; }

return < button onClick = { handleClick } > { count } </ button > ; }

Enter fullscreen mode

Exit fullscreen mode

Click it once, and the counter shows 1 , not 3.

It's not a React bug. It's how state works, and the same idea explains stuck timers and callbacks that read old values. I rendered every example below with React 19.3 ( react-dom + jsdom) and recorded the actual results.

Video version:

Why: state is a snapshot

count isn't a live variable. It's a constant for the current render .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.