Keeping track of an application’s state is how a single page application (SAP) registers changes and renders them to the user. Unlike a model, view, controller (MVC) framework, SAPs do not redirect the user, and therefore need a way to manage changes coming from the client side. To review MVC frameworks, refer to this guide.
In React, the components themselves can manage their own state and re-render accordingly. This is done via lifecycle methods, which are discussed in depth here. For the purpose of this article, we are going to take a look at how to change state using setState.
This guide assumes basic familiarity with React. To review or learn React basics, this article lists some of the best React learning resources.
What is React setState?
The React setState method is how to change a component’s state with stability. There are some specific guidelines in changing state in React.
- setState can only be called inside a class component. Class components call the
constructor()
method and set an initial state. Then we can change state further down by calling setState.
There are two different types of components in React. There is the functional component and the class component. For our purposes, we are only referencing class components. For further review, check out this article on the differences between functional and class components. - By only calling setState in a class component, we can directly reference the component itself using the this keyword. Calling
this.setState()
is best practice and ensures your code won’t break. - Do not modify state directly. Modifying state directly will not register to React to re-render. The whole point of changing state is to fire a re-rendering of that component to reflect the changes back to the user.
Now, let’s take a look at syntax in the context of these guidelines.
setState React Syntax
Starting with the first guideline, we see that we can only use setState inside a class component. As an example, suppose we have a shopping app and we want to implement a shopping cart. We could set up a class component called Cart. This component will be responsible for managing its own state when a user adds an item to the cart.
class Cart extends React.Component { constructor(props){ super(props); this.state = {shoppingCart: []} }
Breaking down the above code, we declare the class component Cart. Like all class components, we extend React.Component. This is boilerplate React syntax.
Since we want to assign state to this component, we have to call the constructor method. Then, the base constructor is called with super(props). It is possible to see the base constructor not called with props. The official React documentation argues that the base constructor method should always be called with props.
Now that we’ve made it through the required React syntax of constructing a class component to hold state, we are ready to assign our initial state. This is the only time we can directly reference the state. Assigning state by calling this.state = {shoppingCart: [] }
allows us to set our initial state of our shopping cart to an empty array.
React setState Example
In the above section, we looked at the syntax involved in declaring an initial state. Once the state is set in the constructor method, we can render as usual:
class Cart extends React.Component { constructor(props) { super(props); this.state = { shoppingCart: [] } } render() { return ( <div> <h1>Your Shopping Cart</h1> <div>{this.state.shoppingCart}</div> </div> ); } } ReactDOM.render( <Cart />, document.getElementById('root') );
Here, we have a Cart class component with its initial state set and is rendering the cart in the return statement of the render method. Let’s see how we can use setState to update our Cart.
We define a function that will add a new item to our shoppingCart while preserving the previously added items. We use JavaScript’s spread operator (…) to make a copy of the initial state and update it with the new state. This way, the shopping cart will hold all items added.
addItem(newItem) { this.setState({ shoppingCart: [...this.state.shoppingCart, newItem] }) }
The addItem function can be used inside of React’s onClick attribute of a button if we want the user to be able to add that item once a button is clicked. For our purposes, seeing how to use setState in the context of a function is enough.
This article is meant to be an introduction to understand how to use setState and is by no means exhaustive.
Conclusion
In this article, we learned what setState is, some guidelines of how to use it, syntax, and a brief example. This is meant to be a primer article to encourage you to dig deeper and practice updating a components state on your own.
The official React documentation has further examples that will provide more opportunities to practice. Remember that in single page applications, keeping track of a component’s state is essential to rendering changes to the user.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.