...

/

Changing State with this.setState()

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
...