Question

Which are the different forms of setState() and how are they used?

#react

Answer

1. setState(stateChange[, callback]) This performs a shallow merge of stateChange into the new state. Ex.

this.setState({quantity: 2})

2. setState((state, props) => stateChange[, callback]) The first argument is an *updater* function that receives the component state and props at the time the change is being applied. This form is useful when the next state depends on the current state (remember that setState() is asynchronous and multiple calls may be batched together). Ex.

this.setState(state => ({ quantity: state.quantity + 1 })

On the other hand, the optional callback in each of the previous forms is useful when it's necessary to read this.state after the update has been applied (simply reading it after calling setState() doesn't work because the update may not happen immediately, but batched or deferred until later).

[^1]: https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly
[^2]: https://reactjs.org/docs/react-component.html#setstate

Learn

Author

xavi

Reviews
Last
next

Students 1