3

Let say I declare a local state using React hook useState() :

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

Later I would like to update the state and trigger the re-rendering:

  1. Set the state by passing the value
<button onClick={() => setCount(count+1)}
  1. Set the state by passing a callback
<button onClick={() => setCount((prev_count) => prev_count+1)}

What is the difference between these 2 types of update?

  • 1
    Does this answer your question? [lifecycle event state and prevState in react.js](https://stackoverflow.com/questions/39806802/lifecycle-event-state-and-prevstate-in-react-js) – kevin Jan 21 '22 at 09:38
  • Does this answer your question? https://stackoverflow.com/a/70509910/9765167 – Ramesh Reddy Jan 21 '22 at 09:38
  • 1
    This might help https://blog.logrocket.com/react-hooks-cheat-sheet-unlock-solutions-to-common-problems-af4caf699e70/#usestate – mabiyan Jan 21 '22 at 09:58

3 Answers3

2
  1. Passing a callback will provide you the access to current state via callback function argument setCount((curr_count) => curr_count+1) .
  2. If your state updates are batched , using the state value in setCount(count+1) will provide you the stale state, chances are there that you might access the previous state.
Shan
  • 1,468
  • 2
  • 12
2

Here it does not make any difference but once your application grows bigger and you have count used at many places, there is a possibility that multiple setState calls would be happening and queuing up data to be rendered to the DOM, and hence the actual value of count might not be what you think.

This is exactly why it is recommended to use the previous state in the callback. prevState is always a reliable solution without tracing every state update to know what the count is.

Winter
  • 331
  • 1
  • 8
-4

"Using a callback function ensures that you're working with the latest state value, even if multiple state updates occur in a short period of time. This can help avoid potential issues with stale state values or race conditions.

In summary, the main difference between passing a new value directly and passing a callback function as an argument to the set[StateName] function in React is how you update the state and ensure that you're working with the latest state value, especially in cases where state updates are asynchronous or depend on the current state value."

I think it has something to do with some async-await functionality while we integrate with the database!

  • 1
    Using ChatGPT to post answers is forbidden. See https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned – Eric Aya Apr 14 '23 at 16:40