Search⌘ K
AI Features

Changing State with this.setState()

Explore how to change state within React class components using this.setState. Understand why direct state modification fails, how to use objects or updater functions with setState, and learn best practices around batching and callbacks to ensure reliable component updates.

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