Differentiation of React State

If you are interested to learn about the React JSX Attribute

What is State?

The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. For example, let us think of the clock that we created in this article, we were calling the render() method every second explicitly, but React provides a better way to achieve the same result and that is by using State, storing the value of time as a member of the component’s state.

The state is an updatable structure that is used to contain data or information about the component. The state in a component can change over time. The change in state over time can happen as a response to user action or system event. A component with the state is known as stateful components. It is the heart of the react component which determines the behavior of the component and how it will render. They are also responsible for making a component dynamic and interactive.

A state must be kept as simple as possible. It can be set by using the setState() method and calling setState() method triggers UI updates. A state represents the component’s local state or information. It can only be accessed or modified inside the component or by the component directly. To set an initial state before any interaction occurs, we need to use the getInitialState() method.

For example, if we have five components that need data or information from the state, then we need to create one container component that will keep the state for all of them.

Defining State

To define a state, you have to first declare a default set of values for defining the component’s initial state. To do this, add a class constructor which assigns an initial state using this.state. The ‘this.state‘ property can be rendered inside render() method.https://imasdk.googleapis.com/js/core/bridge3.522.0_en.html#goog_1955046965

Example

The below sample code shows how we can create a stateful component using ES6 syntax.

import React, { Component } from 'react';  
class App extends React.Component {  
 constructor() {  
      super();        
      this.state = { displayBio: true };  
      }  
      render() {  
          const bio = this.state.displayBio ? (  
              <div>  
                  <p><h3>futurefundamentals is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h3></p>   
            </div>  
              ) : null;  
              return (  
                  <div>  
                      <h1> Welcome to futurefundamentals!! </h1>  
                      { bio }   
                  </div>  
              );  
     }  
}  
export default App;  

To set the state, it is required to call the super() method in the constructor. It is because this.state is uninitialized before the super() method has been called.

React state management: What is it and why to use it? | LoginRadius Blog

Changing the State

We can change the component state by using the setState() method and passing a new state object as the argument. Now, create a new method toggleDisplayBio() in the above example and bind this keyword to the toggleDisplayBio() method otherwise we can’t access this inside toggleDisplayBio() method.

this.toggleDisplayBio = this.toggleDisplayBio.bind(this);  

Example

In this example, we are going to add a button to the render() method. Clicking on this button triggers the toggleDisplayBio() method which displays the desired output.

import React, { Component } from 'react';  
class App extends React.Component {  
 constructor() {  
      super();        
      this.state = { displayBio: false };  
      console.log('Component this', this);  
      this.toggleDisplayBio = this.toggleDisplayBio.bind(this);  
      }  
      toggleDisplayBio(){  
          this.setState({displayBio: !this.state.displayBio});  
          }  
      render() {  
          return (  
              <div>  
                  <h1>Welcome tofuturefundamentals!</h1>  
                  {  
                      this.state.displayBio ? (   
                          <div>  
                              <p><h4>futurefundamentalsis one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h4></p>  
                              <button onClick={this.toggleDisplayBio}> Show Less </button>  
                        </div>  
                          ) : (  
                              <div>  
                                  <button onClick={this.toggleDisplayBio}> Read More </button>  
                              </div>  
                          )  
                  }  
             </div>  
        )  
    }  
}  
export default App;  

Difference of Props and State.

We have already learned about Props and we got to know that Props are also objects that hold information to control the behavior of that particular component, sounds familiar to State indeed but props and states are nowhere near be same. Let us differentiate the two.
 

  • Props are immutable i.e. once set the props cannot be changed, while State is an observable object that is to be used to hold data that may change over time and to control the behavior after each change.
  • States can be used in Class Components, Functional components with the use of React Hooks (useState and other methods) while Props don’t have this limitation.
  • While Props are set by the parent component, State is generally updated by event handlers. For example, let us consider the toggle the theme of the GeeksforGeeks {IDE} page. It can be implemented using State where the probable values of the State can be either light or dark and upon selection, the IDE changes its color.

Now we have learned the basics of State and are able to differentiate it from Props. We have also seen a few places where we can use State now all that is left is to know about the basic conventions of using the React State before implementing one for ourselves.
Conventions of Using State in React: 
 

  • State of a component should prevail throughout the lifetime, thus we must first have some initial state, to do so we should define the State in the constructor of the component’s class. To define a state of any Class we can use the sample format below.
    • javascript
    Class MyClass extends React.Component{constructor(props){super(props);this.state = { attribute : "value" };}}
  • 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. For example, if we update the state of any component like the following the webpage will not re-render itself because React State will not be able to detect the changes made. 
     
this.state.attribute = "new-value";
  • Thus, React provides its own method setState(). setState() method takes a single parameter and expects an object which should contain the set of values to be updated. Once the update is done the method implicitly calls the render() method to repaint the page. Hence, the correct method of updating the value of a state will be similar to the code below. 
     
this.setState({attribute: "new-value"});
  • The only time we are allowed to define the state explicitly is in the constructor to provide the initial state. 
     
  • React is highly efficient and thus uses asynchronous state updates i.e. React may update multiple setState() updates in a single go. Thus using the value of the current state may not always generate the desired result. For example, let us take a case where we must keep a count (Likes of a Post). Many developers may miswrite the code as below. 
     
this.setState({counter: this.state.count + this.props.diff});
  • Now due to asynchronous processing, this.state.count may produce an undesirable result. A more appropriate approach would be to use the following. 
     
this.setState((prevState, props) =&gt; ({
  counter: prevState.count + props.diff
}));
  • IN the above code we are using the ES6 thick arrow function format to take the previous state and props of the component as parameters and are updating the counter. The same can be written using the default functional way as follows. 
     
this.setState(function(prevState, props){
    return {counter: prevState.count + props.diff};
});
  • 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. For example, let us take the following component state into account. 
     
this.state = {
darkTheme: False,
searchTerm: ''
};
  • The above definition has two attributes we can use a single setState() method to update both together, or we can use separate setState() methods to update the attributes independently. React internally merges setState() methods or updates only those attributes which are needed. 

Differentiation of React State
Show Buttons
Hide Buttons