The function form of setState() should be used when the new state depends on the previous state. This ensures that the state is updated correctly, even if React batches multiple updates. The function takes the current state and props as arguments and returns the new state.
What is setState in React?
Key takeaways:
Class components use
setState, while function components useuseState, a simpler and modern approach.setStateupdates the state and triggers React to re-render the component with the new state. React batches multiplesetStatecalls for performance optimization, meaning updates may not happen immediately.The functional form of
setStateshould be used if the new state depends on the previous state.setStateperforms a shallow merge of the update object into the existing state, preserving other state properties.The
setStatemethod accepts an object or a function to update the state and an optional callback function to run after the state update and re-rendering are complete.Class components require
setStateand life cycle methods, making them more complex. Function components with Hooks likeuseStateare modern, simpler, and preferred.
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
setStatemethod 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 callingsetState—use the function form ofsetState(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 insetStatewill 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.
Syntax of setState
The syntax of the setState is:
setState(updater, [callback])
Parameters of setState
updater: This can be an object or a function.- When passing an object,
setStatemerges it into the current state, and we don’t need access to the latest state values. For example:this.setState({ count: 2 }); - When passing a function, we provide a function with the signature
(state, props) => stateChange. This function receives the currentstateandpropsand returns the updated state. This form is especially useful when the new state relies on the previous state:this.setState((state, props) => { return { count: state.count + props.step }; });
- When passing an object,
callback(optional): An optional callback function that runs after the state has been updated and the component has re-rendered. This can be useful if we need to perform an action after the state change is complete, like focusing an input or logging data.
How to use setState in a React counter component
Let’s create a simple Counter class component with a count state. The component includes two buttons: one increments count by a step value (passed as a prop), and the other resets count to 0.
Code explanation
This example demonstrates how setState makes it easy to manage state changes within React class components. In App.js:
Lines 3–30: We define the
Counterclass component.Line 6: We initialize the state and set
countto0in the constructor.Lines 10–14: The
incrementCountmethod updatescountby adding thestepprop, usingsetStateto ensure the component rerenders with the new state.Lines 17–19: The
resetCountmethod resetscountback to0using thesetStatemethod.Lines 21–29: The
rendermethod displayscountand includes buttons to increment and reset the count. The increment button usesstepas the increment value, which is passed as a prop fromApp.
Lines 32–34: The main
Appfunction renders theCountercomponent, passingstep={1}as a prop, socountincrements by 1 each time.
Knowledge test
Let’s attempt a short quiz to assess your understanding.
What is the primary function of the setState method in React class components?
It updates the component’s state and immediately rerenders the component.
It initializes the component’s state.
It updates the component’s state and triggers the rerendering of the component with the new state.
It is used to manage local variables in a component.
React function components vs. class components
React offers both functional components and class components. With the addition of Hooks, function components have become the preferred choice for many developers due to their simplicity and ease of use. Hooks, such as useState, enable functional components to manage state and side effects without needing the setState method used in class components. For beginners especially, function components tend to be more intuitive, aligning with modern React practices.
Conclusion
In short, setState is essential for handling state updates in React class components. By managing the state effectively with setState, we can create responsive and interactive UIs in React. Using both the object and function forms of setState provides flexibility in handling synchronous and asynchronous updates, allowing React to optimize rerendering for better performance. Understanding how setState works and when to use each form is fundamental for effective state management in React class components.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
When should we use the function form of setState() in React?
Can we use setState() in functional components?
What is the importance of setState() for React performance?
Free Resources