init state without constructor in react

I have 2 question, what is state here?

An instance property, like setting this.state = {value: 0}; in a constructor. It’s using the Public Class Fields proposal currently at Stage 2. (So are increment and decrement, which are instance fields whose values are arrow functions so they close over this.)

is that a local variable?

No.

where does the prevState come from? why arrow function is used in setState? isn’t it’s easy to just do this.setState({value:’something’})?

From the documentation:

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

…which is exactly what the quoted code is doing. This would be wrong:

// Wrong
increment = () => {
  this.setState({
    value: this.state.value + 1
  });
};

…because it’s relying on the state of this.state, which the above tells us not to; so the quoted code does this instead:

increment = () => {
  this.setState(prevState => ({
    value: prevState.value + 1
  }));
};

Here’s proof that React may batch calls in a non-obvious way and why we need to use the callback version of setState: Here, we have increment and decrement being called twice per click rather than once (once by the button, once by a span containing the button). Clicking + once should increase the counter to 2, because increment is called twice. But because we haven’t used the function callback version of setState, it doesn’t: One of those calls to increment becomes a no-op because we’re using a stale this.state.value value:

class Counter extends React.Component {
  state = { value: 0 };

  increment = () => {
    /*
    this.setState(prevState => ({
      value: prevState.value + 1
    }));
    */
    console.log("increment called, this.state.value = " + this.state.value);
    this.setState({
      value: this.state.value + 1
    });
  };
  
  fooup = () => {
    this.increment();
  };

  decrement = () => {
    /*
    this.setState(prevState => ({
      value: prevState.value - 1
    }));
    */
    console.log("decrement called, this.state.value = " + this.state.value);
    this.setState({
      value: this.state.value - 1
    });
  };
  
  foodown = () => {
    this.decrement();
  };

  render() {
    return (
      <div>
        {this.state.value}
        <span onClick={this.fooup}>
          <button onClick={this.increment}>+</button>
        </span>
        <span onClick={this.foodown}>
          <button onClick={this.decrement}>-</button>
        </span>
      </div>
    )
  }
}

ReactDOM.render(
  <Counter />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

With the function callback, it works correctly (no calls to increment become no-ops):

class Counter extends React.Component {
  state = { value: 0 };

  increment = () => {
    this.setState(prevState => {
      console.log("Incrementing, prevState.value = " + prevState.value);
      return {
        value: prevState.value + 1
      };
    });
  };
  
  fooup = () => {
    this.increment();
  };

  decrement = () => {
    this.setState(prevState => {
      console.log("Decrementing, prevState.value = " + prevState.value);
      return {
        value: prevState.value - 1
      };
    });
  };
  
  foodown = () => {
    this.decrement();
  };

  render() {
    return (
      <div>
        {this.state.value}
        <span onClick={this.fooup}>
          <button onClick={this.increment}>+</button>
        </span>
        <span onClick={this.foodown}>
          <button onClick={this.decrement}>-</button>
        </span>
      </div>
    )
  }
}

ReactDOM.render(
  <Counter />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

In this case, of course, we can look at the render method and say “Hey, increment will get called twice during a click, I’d better use the callback version of setState.” But rather than assuming it’s safe to use this.state when determining next state, best practice is not to assume that. In a complex component, it’s easy to use mutator methods in a way that the author of the mutator method may not have thought of. Hence the statement by the React authors:

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

Leave a Comment