ghophri
ghophri

Reputation: 221

React Hook: setState usage

What's the difference between

1

const [state, setState] = useState(0)

setState(state+1)

2

const [state, setState] = useState(0)

setState(...prevState => prevState+1)

Upvotes: 0

Views: 261

Answers (1)

norbitrial
norbitrial

Reputation: 15166

In the first option, based on the documentation:

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

In the second option, called functional update:

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

So basically if you'd like to be sure your state will be updated based on the previous state, you need to use the second option.

Read further in the official documentation of useState.

I hope this clarifies!

Upvotes: 3

Related Questions