Given the following snippet extracted from a React class component:
constructor(props) {
super(props)
this.state = { active: true }
}
deactivate = () => {
this.setState({ ...this.state, active: false })
}
What is the aim of the spread operator into the stopCounter() method? The application also works removing it:
deactivate = () => {
this.setState({ active: false })
}
Both works in that case, but you don't need to use that. Just setting the state will be okay:
this.setState({active: false})
But let me explain what if you have nested level of states like:
state = {
foo: {
a: 1,
b: 2,
c: 3
}
}
And when you need to update the foo's c state only, then you'll need to merge the state like:
this.setState({ foo: {
...this.state.foo,
c: 'updated value'
}})
So, the spread syntax merges object with later object. It's similar to Object.assign.
The goal is just set active
to false
and keep the rest with no modifications.
You can edit a part of your state just passing the required names, and skipping the rest.
The second snippet works because React is implicitly doing the spreading for you. Per React's documentation for setState
:
You may [...] pass an object as the first argument to
setState()
:setState(stateChange[, callback])
. This performs a shallow merge of stateChange into the new state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With