Using State correctly Flashcards

1
Q

Do not modify state directly

A

Use setState(). The only place you can assign state is in the constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

State updates may be asynchronous

A

React may batch multiple setState() calls into a single update for performance. Because this.props & 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((state, props) => ({
  counter: state.counter + props.increment
}));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

State updates are merged

A

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 = {
      posts: [],
      comments: []
    };
  }

Then you can update them independently with separate setState() calls:

  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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly