4

The react.js site has the following code on this page:

const [count, setCount] = useState(0);
...
<button onClick={() => setCount(count + 1)}>

But since count is updated based on its previous value, shouldn't the second line be

<button onClick={() => setCount(prevCount => prevCount + 1)}>
user13647644
  • 43
  • 1
  • 1
  • 3
  • `count` is never updated based on its previous value. it gets updated based on its current value. – aytek Dec 24 '20 at 13:41

1 Answers1

6

It usually isn't necessary.

The stateful count variable that the currently active click listener closes over will contain, at any given point in time, the current count. If you click 3 times, the component will re-render 3 times, and the count closed over by the currently attached listener will contain 3.

The time where you would need to use the callback form you're thinking of would be if you wanted to pass the setter function somewhere else (such as to a child component) and didn't want the child component to have to take the count as a prop as well - that makes for some messy boilerplate, especially when components get pretty nested.

You might also use the callback form in the current component if you called the callback in a function that doesn't get a new closure every render, such as for useEffect:

useEffect(() => {
  setInterval(() => {
    setCount(prevCount => prevCount + 1);
  }, 1000);
}, []);

Because the effect hook there only runs on mount, the count variable it could see would be only the initial 0 value - so you have to use the callback form instead.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320