What Is State In React?

React state is a unique and important feature that represents a component’s current data at any given time. It is the component’s private memory, which stores values that can change during the application’s lifecycle.

All these changes can be applied by user interactions like typing in an input field, API responses, or any internal events.

On the other hand, React props are used to pass data from a parent component to a child. It’s also a read-only method. But the state is fully owned and managed within the component itself. It means the component has complete control over how and when the state changes.

Whenever, a component’s change the state, so React automatically re-renders that component to reflect the updated data in the display. This method makes React applications dynamic and interactive without manually manipulating the DOM element.

Why is State Important?

If we don’t use state, components would be static and show the same data every time. State provides the ability to adapt in real-time, making them responsive to user actions and system events.

Key Characteristics of State in React

Here, the important characteristics available that are used in React state are.

1) Component-Specific

A state belongs to the component where it is defined. It means, each component manages its own state independently, and other component cannot directly access or modify this state, which ensures data encapsulation and prevents useless changes

However, if you want to use the parent state in a child component, you can pass it down as props. This method allows parent components to share data without breaking the one-way data flow in React.

For example:

If a parent component has a “username” state, it can pass it to a child component as a prop; however, the child cannot directly change it. Only the parent can modify this state.

2) Mutable

State is mutable, which means it can be updated after the component has been rendered. For example, when a user clicks a button to increase a counter, the state changes, and React updates the UI automatically.

3) Asynchronous Updates

Asynchronous updates mean it doesn’t update immediately. React schedules these updates and may combine multiple state changes for better performance. This process is called batching.

Imagine you click a button five times quickly. If React updated the state immediately for every click, it would re-render the component five times in a row. That would slow down the app.

To avoid this problem, React batches multiple state updates together and then re-renders only once.

Code Example:

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

function handleClick() {
setCount(count + 1);
console.log(count); // This will still show the old value!
}

In this code, if count was 0, and you click the button, you might expect console.log(count) to show 1, but it will still show 0. This happens because React has not yet updated the state; it’s still in the process of batching updates.

How to solve this problem?

Correct Code Example:

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

function handleClick() {
setCount(prevCount => prevCount + 1);
console.log(count); // Still old value here, but update will be correct
}

3) Triggers Re-Rendering

Whenever the state changes completely, React shows the latest data on the screen. This process is automatic; you don’t need to manually update the DOM like in vanilla JavaScript.

How To Use State in Class Component?

A state is a special object in React class components that holds data and changes over time. We define the initial state in the constructor, and whenever we need to update it, we use the setState() method.

Breaking Down the Example:

import React, { Component } from 'react';

class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 }; // Initial state
}

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

render() {
return (
<div>
<p>Current Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}

export default Counter;

Code explanation:

  • The constructor method is the first thing that runs when the component is created. Inside it, we define the initial state using this.state method.
  • Then, we never modify this.state directly. Instead, we use setState() method to do this process.
  • The render() method decides what will be displayed on the screen.

How To Use State in Functional Components with useState Hook?

Before React 16.8, functional components were stateless; they could only display data passed through props. They couldn’t manage their own state like class components. But with the introduction of Hooks, React gave functional components the power to use state, and the useState hook is the most commonly used for this purpose.

Code Example:

import React, { useState } from 'react';

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

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

return (
<div>
<p>Current Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}

export default Counter;

In this code:

  • useState(0) sets the initial value of state to 0.
  • count calculates the current state value.
  • setCount will update the state.
  • setCount((prevCount) => prevCount + 1): we call setCount and pass a function that takes the previous value (prevCount) and returns a new value.

Common Patterns with React State

1) Multiple State Variables

We are not limited to a single state variable in functional components. You can call useState multiple times to manage different pieces of data separately.

For example:

const [name, setName] = useState('');
const [age, setAge] = useState(0);

Here, the name variable manages a string value, such as a user’s name. And age manages a numeric value, such as a user’s age.

2) Using Objects in State

We can also store related values together in a single state object.

Code example:

const [user, setUser] = useState({ name: '', age: 0 });

const updateName = (newName) => {
setUser((prevUser) => ({
...prevUser, // Keep other properties intact
name: newName // Update only the name
}));
};

This method is useful for grouping them in an object, which keeps the state structured. However, you must use the spread operator (…prevUser) to keep existing properties; otherwise, they’ll be lost during the update.

3) Conditional State Update

Sometimes, we want to update specific conditions instead of the entire state. For example, allow the user to increase a value only if it’s below a certain limit.

Code example:

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

const increment = () => {
if (count < 10) {
setCount(count + 1);
}
};

Example of Conditional Rendering Based on State

Conditional rendering in React involves determining what to display on the screen based on specific conditions. The state plays a major role here because it controls the component’s behaviour and determines which elements are visible.

Example: Day/Night Mode Toggle

import React, { useState } from 'react';

function ThemeToggle() {
const [isDay, setIsDay] = useState(true);

const toggleTheme = () => {
setIsDay((prev) => !prev);
};

return (
<div style={{
backgroundColor: isDay ? '#fffbe6' : '#1e1e1e',
color: isDay ? '#000' : '#fff',
height: '100vh',
textAlign: 'center',
paddingTop: '50px'
}}>
<h1>{isDay ? 'Good Morning!' : 'Good Night!'}</h1>
<button onClick={toggleTheme}>
Switch to {isDay ? 'Night' : 'Day'} Mode
</button>
</div>
);
}

export default ThemeToggle;

Code explanation:

  • isDay is a state variable that starts as true (Day mode).
  • setIsDay is used to update the value of isDay.
  • When the button is clicked, this function switches the value of isDay.
  • If isDay was true, it becomes false (Night mode), and vice versa.

Real-Life Mini Project: Emoji Mood Changer

Now, we are building a mini project where the user clicks a button to change the mood emoji using the useState Hook.

Complete Code:

import React, { useState } from "react";

function EmojiMoodChanger() {
// State to store current mood
const [mood, setMood] = useState("😊");

// List of moods
const moods = ["😊", "😢", "😠", "😲"];

// Function to change mood randomly
const changeMood = () => {
const randomIndex = Math.floor(Math.random() * moods.length);
setMood(moods[randomIndex]);
};

return (
<div style={{
textAlign: "center",
paddingTop: "50px",
backgroundColor: "#f0f8ff",
height: "100vh"
}}>
<h1>How's your mood today?</h1>
<p style={{ fontSize: "80px", margin: "20px 0" }}>{mood}</p>
<button
onClick={changeMood}
style={{
padding: "10px 20px",
fontSize: "18px",
cursor: "pointer",
borderRadius: "8px"
}}
>
Change Mood
</button>
</div>
);
}

export default EmojiMoodChanger;
  • Could you understand this code logic on your own and write it in your own words?

Exercise For Student Practice

“Dynamic Character Counter with Color Indicator”

Your Task: Create a small React app where:

  • There is a text input field.
  • Below it, shows the number of characters typed in real time.
  • If the character count is:
    • 0 → Show “Start typing…” in gray.
    • 1-20 → Show count in green.
    • 21-50 → Show count in orange.
    • More than 50 → Show count in red.

Please write this code yourself to understand the logic of React’s useState.

Also Learn Other Topics:

Leave a Comment