In React, components can have a state, which represents the dynamic data that changes over time. For example, a state might store information like whether a user is logged in, the color to display for a button, or the current count in a counter component.
The state directly influences what is displayed in the UI. When the state changes, React rerenders the component to reflect the updated state in the UI.
In class components, the setState
method is used to update the component’s state. In function components, we will instead use the useState()
Hook for managing state. You can learn more about useState
here.
How does setState
work in React?
The setState
method in React allows us to enqueue changes to the component’s state and informs React that the component and its children need to rerender with the updated state. This is the primary method you should use for state management in class components to update the UI. Notably:
-
Asynchronous updates: The setState
method doesn’t always update the component immediately. For performance reasons, React may batch multiple state updates and defer rerendering until later. As a result, we should not rely on the current state directly after calling setState
—use the function form of setState
(described below) if the new state depends on the previous state.
-
Shallow merge: When we call setState
, React performs a shallow merge of the object you provide with the current state, rather than replacing the entire state object. This means that only the properties you specify in setState
will be updated, leaving other properties in the state intact. This shallow merging approach is useful for managing complex state without having to recreate all state properties every time.