Reputation: 1317
I read a lot of articles about using functional setState
like that:
this.setState((state, props) => ({ counter: state.counter + props.increment }));
but when do we actually need to use it as an object like that:
this.setState({quantity: 2})
Is there a significant reason why we should use an object in setState
in normal cases vs using it as a function?
Upvotes: 1
Views: 551
Reputation: 4937
In Javascript, a function is an object.
Therefore, technically, there is no difference between
a function being passed as the argument to setState and
an object being passed as the argument for the setState method.
However, a function may be used instead of an object for the purpose of formatting or for performing temporary calculations before updating the state attributes.
Example use cases for function in place of an object:
Upvotes: 1
Reputation: 8034
The norm is to use an object, it's also less code and easier to read. The only reason u want to use a function setState is when u need to access the previous state.
consider the following example
// you have a switch state
state = {
checked: false
}
// .. and later in an onChange method
onChange = () => {
const {checked} = this.state;
// this is problematic because react works in an async fashion, so it could be that when this function was called checked was false, however it was only executed later when checked was actually true
this.setState({checked: !checked}
// on the other hand this form is safe, even if things were happening async, you are safe because you act on the most updated state
this.setState(prvState => {...prvState, checked: !prvState.checked})
}
Upvotes: 4