Search code examples
javascriptreactjsreact-hooksuse-state

What's the difference between passing a value and passing a callback in a React setState hook function?


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?


Solution

  • 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.