The Wayback Machine - https://web.archive.org/web/20240913185815/https://www.geeksforgeeks.org/reactjs-state/
Open In App

ReactJS State

Last Updated : 14 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

What is a React State?

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.

Creating State Object

Creating a state is essential to building dynamic and interactive components.

We can create a state object within the constructor of the class component.

JavaScript
import React from 'react';

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            brand: 'Ford', // Example property in the state
        };
    }

    render() {
        return (
            <div>
                <h1>My Car</h1>
                {/* Other component content */}
            </div>
        );
    }
}

export default MyComponent;

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

In React, a State object can be updated using setState() method.

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 State

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:

using react state to make counter app



Previous Article
Next Article

Similar Reads

How to update nested state properties in ReactJS?
There are the following approaches to update nested state properties in ReactJS: Approach 1: We can create a dummy object to perform operations on it (update properties that we want) then replace the component's state with the updated object.Approach 2: We can pass the old nested object using the spread operator and then override the particular pro
2 min read
How to update parent state in ReactJS ?
We can pass a function setting the state from the parent to the child component as a prop. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app foldernameStep 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldernameProject Structure: It w
1 min read
How to set Parent State from Children Component in ReactJS?
We can set Parent State from Children Component in ReactJs using the following approach. Prerequisite: State introduction in ReactJS We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting.We will create a function in parent to set the state with the given input.We will pass that f
3 min read
Lifting State up in ReactJS
Prerequisite: ReactJs, State, Props Lifting up the State: As we know, every component in React has its own state. Because of this sometimes data can be redundant and inconsistent. So, by Lifting up the state we make the state of the parent component as a single source of truth and pass the data of the parent in its children. Time to use Lift up the
2 min read
Unstated Next - Lightweight State Management Library For ReactJS | Part - 2 | Shopping Cart
In the previous published article, we have explained everything you need to know about Unstated Next that recommends you to read that article if you haven't. In this article, we are going to build a simple shopping cart application having the functionality to add, remove, update and display any item in the cart. Prerequisite: Have basic knowledge a
4 min read
Unstated Next - Lightweight State Management Library For ReactJS | Part - 1
You might have used many state management libraries for ReactJs like Redux, Recoil MobX, and even Unstated but have you ever thought you can manage your entire application state just by using 300 bytes of code. It can possible by using the Unstated-next state management library. What is Unstated Next? It is a lightweight state management library bu
4 min read
How to get previous state in ReactJS Functional Component ?
To get the previous state in ReactJS Functional Component we can use the previous value of the state while using the set state method. State can only be directly accessed in the class component so we will be using the react useState hook to accomplish the task. PrerequisitesReact JSReact JS functional componentsReact useState HookSteps to create Re
2 min read
How to save new state to local JSON using ReactJS ?
To save data in local storage is a common task while creating a react application to store the user-specific data. We can save new state to local JSON using react in local storage of the browser and access that information anytime later. Prerequisites:React JSNPM &amp; Node.jsJavaScript localStorageApproach:In React to save a new state to local JSO
2 min read
How to set state with a dynamic key name in ReactJS ?
When working with ReactJS, managing state is a fundamental aspect of building dynamic and interactive user interfaces. In some cases, you may encounter situations where you need to set a state with a dynamic key name, rather than a fixed one. This can be particularly useful when dealing with dynamic data or when you want to update the state based o
2 min read
How to update the State of a component in ReactJS ?
To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content. Prerequisites: NPM &amp; Node.jsReact JSReact StateReact JS Class ComponentsReact JS Functional ComponentsA
3 min read
How to lift state two levels up in ReactJS ?
We want to lift the state two levels up such that when an event occurs at the lower level component then it should affect the state two levels up. For example, there are three components X, Y, and Z. X is the parent of Component Y, and Component Y is the parent of Component Z. Prerequisites:NodeJS or NPMReact JSApproach:When some event occurs in co
2 min read
How to update state to re-render the component in ReactJS ?
In React, when the state is updated it initiates to re-render the component and its child components to update the new data on the UI of the application. PrerequisitesReact Functional ComponentsReact Class ComponentsReact HooksUpdate state to re-render the component in React:There are different ways in the functional and class components to update
3 min read
How to Use Flux to Manage State in ReactJS?
State management in ReactJS is important for building dynamic and responsive applications. Flux, an architecture for managing state, provides a structured approach to handle data flow and state changes efficiently in React applications. In this article, we will explore the Flux to Manage State in ReactJS with proper examples. Prerequisites:ReactJSJ
5 min read
How to locally manage component's state in ReactJS ?
Any component in React JS majorly depends on its props and state to manage data. A component's state is private to it and is responsible for governing its behavior throughout its life. A state is nothing but a structure that records any data changes in a react application. It can be used for storing values, form inputs, data from an API, etc. This
2 min read
Unstated Next - Lightweight State Management Library For ReactJS | Part - 3 | Shopping Cart
We have implemented a shopping cart using Unstated Next In this article we are gonna learn how to handle states of more than one component in a React application using Unstated Next. Prerequisites:NodeJS or NPMReact JSSteps to Create the React Application And Installing Module:Step 1: Create a new react app. npx create-react-app shopping-cartStep 2
5 min read
ReactJS State vs Props
In React props are a way to pass the data or properties from parent component to child components while the state is the real-time data available to use within only that component. States and props are two of the most important concepts of React and everything in React is based upon them. But before jumping into State and Props we need to know abou
4 min read
How To Delete An Item From State Array in ReactJS?
It is important to manage the state in ReactJS for building interactive user interfaces. Sometimes when we work with arrays, we need to remove an item from these arrays. A common use case is deleting an item from an array stored in the component’s state. In this article, we’ll explore different ways to handle this operation in ReactJS. Below are di
3 min read
Semantic-UI Form Read-Only Field State
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. A form is the section of a document that contains a number of input fields such as text field,
2 min read
Semantic-UI Step Active State
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. In this article, we are going to learn about Step Active State. It is equipped with pre-built semantic components that help create resp
2 min read
Semantic-UI Image Disabled State
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. Semantic UI has a bunch of components for user interface design. One of them is “Image”. Images are an important tool to depict informa
2 min read
CSS | Animation to Change the Hover State of a Button/Image
1. To change the color/size of the button in hover state. Approach: Set the animation and time duration of hover stateSet background color using @keyframes Syntax: button:hover { animation-name: background-color; animation-duration: 500ms; } @keyframes background-color { 100% { background-color:#4065F3; } } Examples: C/C++ Code &lt;!DOCTYPE html
2 min read
React Suite Dropdown Option Active State
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Dropdown component allows the user to provide navigation that uses a select picker if you want to select a value. React Suite Dropdown Option Active State helps to set a value active by default in a Dropdown men
3 min read
How to get button toggle state within HTML?
Toggle buttons are basically on/off buttons. A button can be switched from on to off state and vice-versa. This process is called toggling.Examples of toggle button: The buttons on our switchboards are the best example of toggle buttons.Some of the buttons on our phones- the torch button, the mobile data button, the wifi button, flight mode, Blueto
2 min read
How to change state continuously after a certain amount of time in React?
To change a state continuously after a certain amount of time is required in a few cases for the toggling. First, make a function that is responsible for changing the state of the component. Then call the function from the constructor method for the first time. Use the set interval method inside the function to change the state after a fixed amount
2 min read
How to change the state of react component on click?
To change the state of the React component is useful when you are working on a single page application, it simply replaces the content of the existing component for the user without reloading the webpage. We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing s
2 min read
How to update the state of react components using callback?
The state is mutable in react components. To make the React applications interactive we almost use state in every react component. The state is initialized with some value and based on user interaction with the application we update the state of the component at some point in time using setState method. setState method allows to change of the state
3 min read
How to bind 'this' keyword to resolve classical error message 'state of undefined' in React?
The 'this' keyword in JavaScript is always being somewhat tough to understand for learners. Basically this keyword inside a function is determined by looking at how the method is actually invoked. Usually in JavaScript, we invoked the method using syntax obj.method(). In this case, the value of 'this' keyword inside the method function is the objec
3 min read
Alternative of ng-checked to get the checkbox's state in AngularJS
In this article, we will see how to get the state of the checkboxes in AngularJS. This task can be performed with the help of the ng-model directive that helps to bind input, select and textarea, and store the required user value in a variable and we can use that variable whenever we require that value. Approach: ng-model is used to get the selecte
2 min read
Node.js http2stream.state Method
The http2stream.state is an inbuilt application programming interface of class Http2Stream within http2 module which is used to get the miscellaneous information about the current state of the Http2Stream. Syntax: const http2stream.state Parameters: This method does not accept any parameter. Return Value: This method returns the miscellaneous infor
3 min read
What is Initialize state in amp-bind of Google AMP ?
The amp-bind is made in such a way that any document using it has a mutable JSON data or state. This data can be manipulated using amp-state. Your data is not evaluated on page load but dynamically evaluated along with user input. It has various state and they have their own variable. In this article, we will talk about the initial state of the ele
2 min read