Table of contents
1.
Introduction
2.
What is State in ReactJS?
2.1.
Key Features of State
3.
Example
4.
Creating State Object
4.1.
Functional Components
4.2.
Class Components
5.
Conventions of Using State in React
5.1.
Example of Incorrect State Mutation
5.2.
Correct Way
6.
Updating State in React
6.1.
Functional Components
6.2.
Class Components
6.3.
Example
7.
Managing Complex State
7.1.
Example
8.
State vs. Props
9.
Frequently Asked Questions
9.1.
What is the difference between props and state in React? 
9.2.
Why should we not modify state directly in React? 
9.3.
How can I manage complex state in React? 
10.
Conclusion
Last Updated: Jan 3, 2025
Easy

​​State in ReactJS

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In ReactJS, State is an important concept that helps in making your website or app interactive. State is used to store information that can change, like user input or data from a server. When the state changes, React automatically updates the display to reflect the new data.

​​State in ReactJS

In this article, we will discuss what state is in ReactJS, how to create and update it, and how to manage complex states effectively. 

What is State in ReactJS?

State in ReactJS refers to a special object used to hold data or information about a component. Unlike props, which are immutable and passed down from parent to child components, state is local and mutable, meaning it can be changed within the component itself. State plays a crucial role in determining how a component behaves and what it displays on the screen.

Key Features of State

  1. Mutable: State can be updated, allowing components to respond to user actions or other events.
     
  2. Local: State is specific to a component and is not shared directly with other components.
     
  3. Triggers Re-rendering: Updating the state automatically triggers a re-render of the component, ensuring the UI is in sync with the data.

Example

import React, { useState } from 'react';
function Counter() {
    const [count, setCount] = useState(0); // Declaring state
    return (
        <div>
            <h1>Counter: {count}</h1>
            <button onClick={() => setCount(count + 1)}>Increase</button>
        </div>
    );
}
export default Counter;


Explanation

  • useState(0) initializes the state variable count with a value of 0.
     
  • setCount is used to update the value of count.
     
  • Clicking the "Increase" button increments the counter and updates the UI automatically.

Creating State Object

State in class components and functional components is managed differently. While functional components use the useState hook, class components rely on the this.state object.

Functional Components

import React, { useState } from 'react';

function Example() {
    const [text, setText] = useState('Hello, World!');

    return (
        <div>
            <p>{text}</p>
            <button onClick={() => setText('React is awesome!')}>Change Text</button>
        </div>
    );
}
export default Example;

Class Components

import React, { Component } from 'react';
class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
            text: 'Hello, World!'
        };
    }

    changeText = () => {
        this.setState({ text: 'React is awesome!' });
    };


    render() {
        return (
            <div>
                <p>{this.state.text}</p>
                <button onClick={this.changeText}>Change Text</button>
            </div>
        );
    }
}

export default Example;

Conventions of Using State in React

To use state effectively in React, follow these conventions:

  1. Initialize State Properly: Always initialize state in the constructor (for class components) or using useState (for functional components).
     
  2. Keep State Simple: Avoid over-complicating state by including unnecessary data. Use separate state variables for unrelated pieces of information.
     
  3. Avoid Direct Mutations: Never modify state directly. Always use setState or state updater functions to ensure React handles updates correctly.

Example of Incorrect State Mutation

this.state.text = 'New Text'; // Incorrect

Correct Way

this.setState({ text: 'New Text' });

Use Functional Updates When Necessary: For complex state updates, use the functional form of setState or useState.

Updating State in React

React provides two methods for updating state:

Functional Components

Using the setState updater function:

setState((prevState) => prevState + 1);

Class Components

Using the this.setState method:

this.setState((prevState) => ({ count: prevState.count + 1 }));

Example

function Counter() {
    const [count, setCount] = useState(0);


    const increment = () => {
        setCount((prevCount) => prevCount + 1);
    };


    return (
        <div>
            <h1>{count}</h1>
            <button onClick={increment}>Increment</button>
        </div>
    );
}

Managing Complex State

Sometimes, components require managing multiple interrelated pieces of state. This can be done using objects or external libraries like Redux for advanced state management.

Example

function UserProfile() {
    const [user, setUser] = useState({
        name: 'John Doe',
        age: 25,
        location: 'New York'
    });
    const updateAge = () => {
        setUser((prevUser) => ({
            ...prevUser,
            age: prevUser.age + 1
        }));
    };
    return (
        <div>
            <h2>{user.name}</h2>
            <p>Age: {user.age}</p>
            <p>Location: {user.location}</p>
            <button onClick={updateAge}>Increase Age</button>
        </div>
    );
}


Explanation

  • setUser is used to update the user object while preserving its existing properties using the spread operator (...).

State vs. Props

AspectStateProps
MutabilityState is mutable and can be changed within a component using the setState() method.Props are immutable and cannot be modified by the component receiving them.
ScopeState is internal to a component and is used to store and manage data that can change over time.Props are external to a component and are passed down from a parent component to its children.
InitializationState is initialized in the constructor of a class component or using the useState hook in functional components.Props are passed to a component as attributes when it is rendered by its parent.
Re-render TriggerChanges in state trigger a re-render of the component and its children.Changes in props also trigger a re-render of the component receiving them.
Use CasesState is used to handle interactivity, form inputs, toggling visibility, and other dynamic behavior within a component.Props are used to pass data and configuration from a parent component to its children, allowing for reusability and composition.

Frequently Asked Questions

What is the difference between props and state in React? 

Props are immutable and passed from parent to child components, while state is mutable and managed locally within a component.

Why should we not modify state directly in React? 

Directly modifying state bypasses React's re-rendering process, which can lead to inconsistencies in the UI.

How can I manage complex state in React? 

You can manage complex state using objects, the spread operator, or state management libraries like Redux for larger applications.

Conclusion

State in ReactJS is a fundamental concept for building dynamic and interactive applications. This article covered the basics of state, how to create and update it, and best practices for managing simple and complex state scenarios. Understanding state allows you to build responsive and efficient user interfaces.

You can also check out our other blogs on Code360.

Live masterclass