0

Here's the code that does not work :

import { useState } from "react";

const Counter = () => {

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

const buttonHandler = ()=>{
    setCount(count+1);
    setCount(count+1);
}


return (

    <div >
        {count}
        <button onClick={buttonHandler}>+</button>
    </div>


);

}

I don't really get what is happening under the hood of React. I saw through some videos it would work if I did this:

const buttonHandler = ()=>{
    setCount(prevCount => prevCount+1);
    setCount(prevCount => prevCount+1);
}

But I don't feel like I really get why the first one is not working

Ali
  • 1
  • 1
    You've created a closure over `count` so they both get passed the value of `count` at the time of the last render cycle. Pass a callback to avoid this `setCount(prevCount => prevCount+1);` – pilchard Sep 04 '21 at 22:26
  • Does this answer your question? [useState hook setter incorrectly overwrites state](https://stackoverflow.com/questions/58193166/usestate-hook-setter-incorrectly-overwrites-state) – pilchard Sep 04 '21 at 22:28
  • If I understand, the `setCount(count +1)` always refers to the first value of `count` declared in `useState` so thats why it does not work, right ? – Ali Sep 04 '21 at 22:51
  • It refers to the value of `count` at the time the function containing them is declared, which will be at the beginning of each render cycle. So your count will increment, but only by one. By passing a callback React passes the most current state value to the callback avoiding a race condition – pilchard Sep 04 '21 at 23:06

1 Answers1

0

In your function, buttonHandler, setCount isn't changing the value of count immediately. It's just updating the state that is used to set count the next time Counter is rendered.

So if count is 0, calling setCount with a value of count + 1 twice actually results in two calls to setCount with a value of 1.

SteveGreenley
  • 630
  • 1
  • 5
  • 7