Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 })
  }
like image 388
Biomehanika Avatar asked Mar 19 '19 18:03

Biomehanika


3 Answers

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.

like image 56
Bhojendra Rauniyar Avatar answered Oct 31 '22 04:10

Bhojendra Rauniyar


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.

like image 42
alejandrosobko Avatar answered Oct 31 '22 06:10

alejandrosobko


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.

like image 32
Huy Nguyen Avatar answered Oct 31 '22 04:10

Huy Nguyen