What is React State?

A state in React is a special object that represents the current state of a component. Unlike props, which are passed from parent to child components, state is internal and can be changed by the component itself. State is used to manage dynamic data and to trigger re-rendering of components when the state changes. Each component can have its own state, making it a self-contained unit with its own data.

Setting State:

State can be initialised using the useState hook in functional components or via the this.state and this.setState methods in class components.

Example: Creating a counter button to count the number of times the button is clicked.

Javascript




// Functional component using with useState hook
 
import React, { useState } from "react";
 
function Counter() {
    // useState hook
    const [count, setCount] = useState(0);
 
    return (
        <div>
            <p>Count: {count}</p>
            // incrementing the value of the count by 1
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}
 
export default Counter;


Output:

Output

State in Class Components: In class components, state is initialized in the constructor, and setState is used to update it:

Example: Creating a counter button to count the number of times the button is clicked.

Javascript




// Class component with state
import React, { Component } from 'react';
 
class Counter extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }
 
    render() {
        return (
            <div>
                <p>Count: {this.state.count}</p>
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                    Increment
                </button>
            </div>
        );
    }
}
 
export default Counter;


Output:

Output

Understanding React State and Data Flow

React, a very popular JavaScript library used for building user interfaces has the concept of components and they can manage the states efficiently. ReactJs is based on the concept of uni-directional data transfer. In this article, we will understand React State and Data Flow across the application.

Similar Reads

What is React State?

A state in React is a special object that represents the current state of a component. Unlike props, which are passed from parent to child components, state is internal and can be changed by the component itself. State is used to manage dynamic data and to trigger re-rendering of components when the state changes. Each component can have its own state, making it a self-contained unit with its own data....

Data Flow in React JS:

...