React State: Managing Dynamic UI with setState() and Props

Introduction

In the previous article, we learned about JSX, hooks, and props. In this article, we are going to see what a State is, what are its uses, and how a State is different from props in React.

State in React

A State in React can be changed as per the user's action or any other actions. When the state is changed, React re-renders the component automatically to the browser. We can say that the State contains the information that can be changed during the component’s lifecycle. React stores the state of a component in this state. The value of the state can be set in 2 ways depending on the way a component is created.

Below are the two ways by which the value for a state can be set or initialized.

// Using React.createClass
var Counter = React.createClass({
    getInitialState: function(){
        return {counter: 0};
    }
});

or

// Using ES6 classes

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = { counter: 0 };
    }
}

The component state can be changed by calling the following code.

this.setState(data, callback);

In this.setState() method, it performs a shallow merge of data, which then re-renders the component. The data argument under the setState() method contains an object or function that contains keys to be updated. The optional callback parameter under the setState method contains a function.

setState() is asynchronous, it does not immediately update values if the user tries to access this. state immediately after setState(), there are chances to get old values. This method schedules an update, computation is delayed until necessary.

In State, 3 things need to be taken care of

  • The state should not be assigned a value directly other than in the constructor, always use the setState() method to assign value.
  • State updates may be asynchronous, so the user should not rely on state values for calculating the next state value.
  • State updates are shallow merges, In setState() multiple variables may be present so it merges values even though accessed or updated separately.

The state is also stated as local or encapsulated, as it can only be accessed in a function or class that owns it, irrespective of whether it is in stateless or stateful components.

Reconciliation process

React has a process named Reconciliation, this process includes how React updates the DOM after making changes to a component when there is a change in state. When the setState() method is triggered, React creates a new tree containing the React element in the component along with the updated State. This tree is used to find out how a component’s UI should change in response to state change by comparing its element with the previous tree. As React knows which changes need to be done that’s why React will only update that part of DOM making React perform fast.

Demo

In React, here is a demo that uses State. In this demo, we create a component named StateDemo.js under the component folder.

Now, let us add the code as below.

import React from 'react';

class States extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
        this.onClick = this.onClick.bind(this);
    }
    
    render() {
        return (
            <p onClick={this.onClick}>{this.state.count}</p>
        );
    }
    
    onClick() {
        this.setState({ count: this.state.count + 1 });
        console.log(this.state.count);
    }
}

export default States;

Now, in app.js, import your newly created component and define its tag in the App class.

import React, { Component } from 'react';
import './App.css';
import logo from './logo.svg';
import States from './Components/StateDemo';

class App extends Component {
  render() {
    return (
      <p className="App">
        <img src={logo} className="App-logo" alt="logo" />
        <States />
      </p>
    );
  }
}

export default App;

Now, run your application. This will display your output in the browser.

Local host

Now, on clicking on p where 0 is displayed, it will increase the counter based on clicks.

 Counter based

Now, let's introduce a button. On click of this, the counter will get updated.

import React from 'react';

class States extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
        this.onClick = this.onClick.bind(this);
    }

    render() {
        return (
            <p>
                <h1>{this.state.count}</h1>
                <button onClick={this.onClick}>Counter</button>
            </p>
        );
    }

    onClick() {
        this.setState({ count: this.state.count + 1 });
        console.log(this.state.count);
    }
}

export default States;

State In React

Difference between props and State
 

props State
Props make components reusable by giving components the ability to receive data from a parent component. State refers to the local state of a component that can neither be accessed nor modified outside the component. It can only be used and accessed within a component.
Props are passed to the component. The state is managed within the component
Props are used in function parameter State is used as a variable declared in the function body
Props are immutable i.e) their values cannot be changed once assigned States are mutable i.e) their values can be changed within a component
In functional components, props are used, While in the class component, this is. props are used. In functional components, useState() is used While in the class component, this. state is used.
Props provide better performance State gives a performance way worse than that of props
Props are used to pass data to child components The state cannot be used to access from a child component. Rather it uses props.

Points to remember

  • Always use the setState() method to change the value of State; never assign a value directly.
  • For code that needs to be executed after the state is modified, always implement that code in a callback function which is the second parameter in the setState() method.
  • When required to update the state on the previous state value, pass the state as a function value instead of a regular object.

Some FAQs related to the State


What is the difference between State and Props?

As already stated previously, props are properties that are passed to components in the same as functional parameters and cannot be changed while the state is managed within the component and can be changed and updated.

What is the use of setState()?

setState() method is used to schedule the update in the component. This component re-renders when any changes are made in the state.

Why setState() return an incorrect value?

The call to setState() is asynchronous. Any code should not depend on this. State value just after the setState() method is called. It does not update value instantly. So in spite of using an object in setState(), the updater function should be used if values need to be computed.

How are the values that depend on the current value updated?

In the setState() method, the function should be used instead of the object to ensure that the call will always use the current state value.

What does the second argument in setState() used for?

The setState() function’s second argument is a callback function. This callback function is invoked when setState() has finished its execution, and the component is re-rendered. This function contains the statements that need to be executed just after the state is updated.

Conclusion

In this article, we reviewed what a is State its usage, and how it works in React. We also reviewed the difference between props and State. Both have their pros and cons and can be used according to their requirement in our application. In the next article, we are going to learn about the destructuring of props and state and also what is event handling in React and how it works.

Next in this series: Destructing of props and state in React