4

I see some people update state using hook like this:

const [count, setCount] = useState(0)

Way 1: setCount(count + 1)

Way 2: setCount(count => count + 1)

What is the difference between these 2 ways?

coinhndp
  • 2,281
  • 9
  • 33
  • 64
  • Here you have a good explanation: https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback – cccn Aug 12 '19 at 09:13

2 Answers2

4

From the docs:

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

Therefore when updating the state based on the value of the current state it is better to use the callback version.

const [count, setCount] = useState(0); // initial state is 0

If you e.g. update the state multiple times like that in a single handler:

setCount(count + 1); 
// new state will be 1 

setCount(count + 1); 
// new state will still be 1 because updates are async 
// and `count` still is 0 at the time of calling this

Whereas

setCount(count => count + 1); 
// new state will be 1

setCount(count => count + 1); 
// new state will be 2 because the value passed 
// to the callback will include the previous update

If you want to be safe always use a callback when updating based on the current state.

More information can be found in the docs.

trixn
  • 15,761
  • 2
  • 38
  • 55
0

Due to the asynchronous nature of the setter, you should use the function way (way 2) any time your new state depends on the previous state, to prevent funky behaviour.

If your new state doesn't depend on the previous state, you can set it normally without a function.

From the docs:

The ”+” and ”-” buttons use the functional form, because the updated value is based on the previous value. But the “Reset” button uses the normal form, because it always sets the count back to the initial value.

https://reactjs.org/docs/hooks-reference.html

Raicuparta
  • 2,037
  • 15
  • 22