Skip to the content.

Code 301 Continuing Reading Notes 02

State and Lifecycle

Using State Correctly

There are three things you should know about setState().

Do not Modify State Directly

// Wrong
this.state.comment = 'Hello';

// Correct 
this.setState({comment: 'Hello'});

The only place where you can assign this.state is the constructor.

State Updates May Be Asynchronous

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

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

The first code may fail to update the counter. But 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.

State Updates are Merged

When you call setState(), React merges the object you provide into the current state.

For example, your state may contain several independent variables:

constructor(props) {
  super(props);
  this.state = {
    post: [],
    comments: []
  };
}

componentDidMount() {
  fetchPosts().then(response => {
    this.setState({
      posts: response.posts
    });
  });

  fetchComments().then(response => {
    this.setState({
      comments: response.comments
    });
  });
}

The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.








Things I want to know more about

<—BACK