Dev

By Carlos Santana on
Reading time: 3 minutes

LocalState-Rlpee.png

The local state is a fundamental feature of React for creating dynamic components. Local state is only available on class components, and each component manages its own state. You can define the initial value of the state on the component's constructor, and when you update the value of the state, the component will be re-render itself.

Local state is helpful with toggles, for handling forms, and is used to manage information within the same component. It is not recommended to use local state if we need to share data between different components directly, instead, we can use the new React Context API (we will cover that topic in the next posts).

How local state works

Let's define our initial state. Let's see how it works the component's render method when the local state is updated.

Using our Home component, we are going to add a constructor and define our initial state: 

import React, { Component } from 'react';

class Home extends Component {
  constructor() {
    // We need to define super() at the beginning of the constructor to have access to 'this'
    super();

    // Here we initialize our local state as an object
    this.state = {
      name: 'Carlos'
    };
  }

  render() {
    return (
      <div className="Home">
        {/* Here we render our state name */}
        <p>Hi my name is <strong>{this.state.name}</strong></p>
      </div>
    )
  }
}

export default Home;

File: src/components/Home/Home.js

In this example, we are defining our local state in the constructor as an object, and in the render, we are printing the value directly. We are using super() at the beginning of the constructor. This is used to call the parent constructor (React.Component). If we don't include it, we will get an error like this: 

 

StateError-ZR53P.png

After we added super(), we need to define our initial state as a regular object:

this.state = { 
  name: 'Carlos'
};

Updating our local state with this.setState()

Right now, this is just a state that is not being updated. That means that the component will never re-render again. To update the state, we need to use the this.setState() method and pass the new value of the state. We can add a setTimeout to update the name state after 1 second (1,000 milliseconds), so we need to modify our render method like this: 

render() { 
  setTimeout(() => {
    this.setState({
      name: 'Cristina' // Here we update the value of the state
    });
  }, 1000);

  console.log('Name:', this.state.name);

  return (
    <div className="Home">
      <p>Hi my name is {this.state.name}</p> 
    </div>
  ); 
}

If you run this in your browser, you will see the first value of the state is Carlos, and 1 second after this it will change to Cristina. I have added a console.log to log the value of the state name. If you open your browser console, you will see this:

 

RenderState-KQ1ZB.png

Updating our local state in componentDidMount

You're probably wondering why is repeated so many times. It is simple; this is the way React works. Every time we update a state the method render is fired, and in this code, we added a setTimeout which updates the state after a second. That means that the render method is being called every second, causing an infinitive loop. This will affect the performance of our application, and that's why you need to be careful when you update a state. As you can see updating it in the render method is not a good idea. So, where should I update the state? Well, it depends on your application, but for now, I'll show you a method that is part of the React lifecycle called componentDidMount():

Only members can see all the codes
You can Login or Sign Up

File: src/components/Home/Home.js

If you run this code and you see the console, now you will see this:

RenderStateImprovement-qcqK6.png

With componentDidMount, we avoided the infinite loop. The reason why this is a better approach is that componentDidMount is being executed just once when the component is already mounted, and in that method, we are executing our setTimeout and updating the name state only once. In the following posts, we are going to learn more about React lifecycle methods.

avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up