8

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)}>
2
  • 2
    Does this answer your question? Updating and merging state object using React useState() hook. ~ * ~ This fine answer shows an example of when not using a function leads to the wrong behavior. Commented Sep 21, 2023 at 11:26
  • count is never updated based on its previous value. it gets updated based on its current value. That's just playing around with words. The current value will become the previous value as soon as the new state is entered. Commented Sep 21, 2023 at 11:47

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.