Categories
javascript jsx reactjs

Spread operator in React .setState()

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.