Open In App
Related Articles

ReactJS State

Improve Article
Improve
Save Article
Save
Like Article
Like

React JS State is a way to store and manage the information or data while creating a React Application. The state is s JavaScript object that contains the real-time data or information on the webpage.

What is a State in React ?

The state in React is an instance of the React Component Class that 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.

Difference between 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 the 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 but in Functional components we have to use React hooks(useState) to implement states.
  • While Props are set by the parent component, the State is generally updated by event handlers.

Conventions of Using State in React: 

  • The state of a component should prevail throughout its 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.
  • The 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.
  • 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. 
  • State updates should be 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.
  • The only time we are allowed to define the state explicitly is in the constructor to provide the initial state. 

Updating State in React

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});

Correct method to update states

In the below 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((prevState, props) => ({
counter: prevState.count + props.diff
}));

Now let us see an example where we will implement state in React and use the state to create a counter

Example: This example demonstrates the use of React JS state creating a simple counter application.

Javascript




// Filename - index.js
 
import React from "react";
import ReactDOM from "react-dom/client";
 
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }
 
    increment = () => {
        this.setState((prevState) => ({
            count: prevState.count + 1,
        }));
    };
 
    decrement = () => {
        this.setState((prevState) => ({
            count: prevState.count - 1,
        }));
    };
 
    render() {
        return (
            <div>
                <h1>
                    The current count is :{" "}
                    {this.state.count}
                </h1>
                <button onClick={this.increment}>
                    Increase
                </button>
                <button onClick={this.decrement}>
                    Decrease
                </button>
            </div>
        );
    }
}
 
const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);


Output:

gfg


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Complete Tutorials