Changing State with this.setState()

Expand your knowledge about states in React and learn how to access and update them.

To change state within components, React offers a new method for use inside of class components:

this.setState(updatedState);

Whenever the state is supposed to change within the component, this.setState() should be used to achieve this. By calling this.setState(), React understands that it needs to execute lifecycle methods (for example componentDidUpdate()) and thus re-render the component. If we were to change state directly, for example, by using this.state.counter = 1;, nothing would happen initially as the render process would not be triggered. React would not know about its state change.

The this.setState() method might look a little complex at the start. This is also because the old state is not simply replaced by a new state, triggering a re-render, but because many other things take place behind the scenes. Let’s take a look at it step by step.

The function itself can take two different types of arguments:

  1. The first being an object containing the new or updated state properties.
  2. The second being an updater function that returns an object or null if nothing should change.

If you happen to have the same property name in your object as you do in the state, the state value will be overwritten while all other properties will remain the same. To reset properties in the state, their values need to be explicitly set to null or undefined. The new state that is being passed is thus never replaced but merged with the existing state.

Adding a new property to state

Let us have another look at our example from the previous lesson in which we defined the state with a counter property whose initial value was 0. Assuming that we want to change this state and add another date property to pass the current date, we can construct the new object:

this.setState({
    date: new Date(),
});

If an updater function was used instead, our function call would look like this:

this.setState(() => {
  return {
    date: new Date(),
  };
});

Or even shorter:

this.setState(() => ({
  date: new Date(),
});

Finally, our component contains the new state:

{
  counter: 0,
  date: new Date(),
}

Go ahead, and run the following piece of code to visualize this new state in action.

Get hands-on with 1200+ tech skills courses.