ReactJs-Interview-Question icon indicating copy to clipboard operation
ReactJs-Interview-Question copied to clipboard

Why Does count Not Increment Correctly on Multiple Clicks?

Open jainaakash1002 opened this issue 9 months ago • 3 comments

Q53 :- What is the output of the following code snippet when the "Click me" button is clicked twice? function App() { const [count, setCount] = React.useState(0);

return (

You clicked {count} times

<button onClick={() => setCount(count + 1)}>Click me
); }

Right Ans : -

Each time the button is clicked:

  1. The event handler runs: setCount(count + 1).
  2. React schedules a re-render with the updated state.
  3. However, the state update is not immediate. The value of count inside the event handler is the value from the last render.
  4. Since count does not update synchronously, clicking twice in quick succession causes both clicks to use the old stale state value.

Step-by-step breakdown:

Click # Current count Expression (setCount(count + 1)) Updated count
0 (initial) 0 - 0
1st Click 0 setCount(0 + 1) 1
2nd Click 0 (stale) setCount(0 + 1) 1 (not 2!)

Thus, after two clicks, count will be 1 instead of 2.

jainaakash1002 avatar Mar 08 '25 07:03 jainaakash1002

I wanted to work on this issue so please assign this task to me.

Thank you.

codesVarun avatar Jun 14 '25 05:06 codesVarun

Try to add a use effect() hook to run everytime count changes so it will probably look something like this

useEffect() { Update count code here , [count]}

Basically the useEffect hook will mount everytime count changes and update count even with multiple clicks

RonmizeJr avatar Nov 14 '25 12:11 RonmizeJr

You may also be able to add prev + 1 so it saves the count and then adds 1

RonmizeJr avatar Nov 14 '25 12:11 RonmizeJr