Understanding React Fundamentals: setState()

Vidhi Agarwal
Alien Brains
Published in
5 min readJul 4, 2020
Photo by Filiberto Santillán on Unsplash

The beauty of React lies in the fact that React Components let you split the user interface (UI) into independent, reusable pieces, so you can think about each piece in isolation. The heart of every React component is its “state”, an object that determines how that component renders & behaves. In other words, “state” is a way of holding, processing and utilizing information that is internal to a given Component and allows you to execute it’s logic and create components that are dynamic and interactive.

It’s one of the most essential thoughts behind React, yet it has a few properties that make it tricky to use and might lead to unexpected behavior in your application. Although once understood, the state system is really going to open the door in react and then the world is your oyster and you get to start working on some pretty interesting applications :)

Adding State to a Class Component

The state is going to contain some amount of information that is relevant to a component and thus when we first create the component we have to initialize our state. That essentially means that when we create a component or an instance of this class we have to initialize the state property.

Figure 1 — React component without state

Adding state to the Learn component above involves defining within the class component, a constructor function that assigns the initial state using this.state. Our state is an object which in our case only has one key called message.

Figure 2 — React Component with state

Now when we define the constructor method it’s going to be automatically called with the prop’s object. Before we do anything else inside this constructor function, we have to go through one little kind of ceremonial step and I say ceremonial because it’s basically just required of us. We have to call a function called super() and we have to pass in the props like so. This is because this is uninitialized before super() has been called.

Updating the State

Only place you can directly write to this.state should be the Components constructor.

State can be updated in response to event handlers, server responses or prop changes. React provides a method called setState for this purpose. setState() alters the component state and tells React that this component and its children need to be re-rendered with the updated state.

The this.setState function, accepts an Object that will be eventually merged into Components current state.

Figure 3 — Updated state

To make this work, we also had to bind the this keyword to the updatedMessage method. Otherwise we couldn’t have accessed this in the method.

setState is Asynchronous

setState() does not immediately mutate this state, rather it creates a pending state transition. Accessing state immediately after calling setState() can potentially return the existing value. It means you can’t call setState on one line and assume state has changed on the next.

Why does this happen?

There are a few reasons for setState() to be asynchronous.

  1. Internal Consistency

Regardless of whether state is updated synchronously, props are not, it means you can’t know props until you re-render the parent component.

The objects provided by React (state, props, refs) are consistent with each other and if you introduce a synchronous setState you could introduce some bugs.

2. Enabling Concurrent Updates

Conceptually, React behaves as if it had a single update queue per component. React could assign different priorities to setState() calls depending on where they’re coming from, like an event handler, a network response, an animation, etc.

Imagine the case you are typing a message, in this case setState() calls in the TextBox component need to be flushed immediately. However, if you receive a new message while you’re typing, it is better to delay rendering than to let the typing stutter due to blocking the thread.

setState() Accepts a Callback!

setState takes a callback as its second argument. Since setState works in an asynchronous way, that means after calling setState the this.state variable is not immediately changed. So if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful.

Figure 4 — this.checkName is passed as callback to setstate

It is important to note that since all updates in a scope are batched, if you have multiple calls to setState each of their callbacks will be called with the fully-updated state.

Common errors that we tend to make

We never do a direct assignment to our state object. It is often seen that newbie developers tend to directly assign to the state object.

The one and only single exception to that rule is when we initialize our state inside the constructor function.

Let’s put a comment here that varies.

Figure 5— An example to find the latitude of the user, displaying the incorrect practices when using setState()

This is the only time we do a direct assignment to this state. Any other time that we want to change, update or otherwise manipulate our state property,we have to always call set state as opposed to doing direct assignment like this right here (in figure 5).

Golden Rules When Using setState()

  1. State should never be updated explicitly.

React uses an observable object as the state that observes what changes are made to the state and helps the component behave accordingly.

2. State updates are independent.

The state object of a component may contain multiple attributes and React allows to use setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each attribute value independently.

3. React is highly efficient and thus uses asynchronous state updates.

React may update multiple setState() updates in a single go.

4. State Updates are Merged.

When you call setState(), React merges the object you provide into the current state.

Hope you all got to learn something new and interesting from this article and understood the fundamentals of state in react.

Explore . Learn . Create

--

--