Does it make any difference if I use return statements in the setState()?

Tell us what’s happening:

Hello,

I was wondering if it makes any difference if use return statements in my code here?

increment() {
    this.setState(state => {
       return state.count +=1;
    });
  }
  decrement() {
    this.setState(state => {
      return state.count -=1;
    });
  }
  reset() {
    this.setState(state => {
      return state.count = 0;
    });
  }

instead of:

  reset() {
    this.setState({
      count: 0
    });
  }
  increment() {
    this.setState(state => ({
      count: state.count + 1
    }));
  }
  decrement() {
    this.setState(state => ({
      count: state.count - 1
    }));
  }

As indicated in the solutions.

Would it affect the performance or could be undesirable in there? My code passed all the tests.

Your code so far


class Counter extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    count: 0
  };
  // change code below this line
  this.increment = this.increment.bind(this);
  this.decrement = this.decrement.bind(this);
  this.reset = this.reset.bind(this);
  // change code above this line
}
// change code below this line
increment() {
  this.setState(state => {
     return state.count +=1;
  });
}
decrement() {
  this.setState(state => {
    return state.count -=1;
  });
}
reset() {
  this.setState(state => {
    return state.count = 0;
  });
}
// change code above this line
render() {
  return (
    <div>
      <button className='inc' onClick={this.increment}>Increment!</button>
      <button className='dec' onClick={this.decrement}>Decrement!</button>
      <button className='reset' onClick={this.reset}>Reset</button>
      <h1>Current Count: {this.state.count}</h1>
    </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.

Challenge: Write a Simple Counter

Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/react/write-a-simple-counter

For an in-depth explanation please refer to the official react documentation about setState.

to sum it up you have two options:
1 - pass a function
or
2 - pass an object and React will perform a shallow merge.

In this example you are passing an Object

  reset() {
    this.setState({
      count: 0
    });
  }

If you choose to pass a function the following is the signature:

(state, props) => stateChange

So yeah, you have to return some value from this function.
Both of the following are valid

// explicit return statement
  this.setState(state => {
     return state.count +=1;
  });

// Parenthesize the body of a function to return an object literal expression:
this.setState(state => ({
      count: state.count + 1
    }));

In case you need a refresh on Arrow function, here’s the documentation.

Hope this helps :+1:

1 Like

Thank you very much!