21
FebState in React : Types of State in React JS
State in React
In React, state is a powerful concept that allows components to manage and track data over time. It helps make your application dynamic by enabling components to respond to user inputs, events, and other changes in the app’s environment. Understanding state is key to building interactive React applications.
In this React tutorial, I will walk you through how the state works in React and how you can use it effectively in your applications. Don’t worry, and we’ll break it down into simple steps so you can grasp the concept with ease. Ready to learn more about a state in React? Let’s dive in!
What is State in ReactJS?
The state in React is a built-in object used to hold data or information about a component. As the state changes over time, the React JS Components re-render to reflect those changes. The state can change in response to user actions or system events, which in turn affects the component's behavior and rendering.
Here's a simple example to help you understand how state works:
class Greetings extends React.Component {
state = {
name: "World"
};
updateName() {
this.setState({ name: "Simplilearn" });
}
render() {
return(
{this.state.name}
);
}
}
In this example:
- State stores information that affects the rendering of the component.
- When the state changes (like when you click a button or something else happens), React automatically re-renders the component.
- The constructor is where the state is usually initialized.
- The state object can contain multiple properties that describe the component's state.
- You change the state with the this.setState() method.
- setState() performs a shallow merge, combining the new and the old state values.
So, state lets you manage data that can change and impact how your component looks and behaves. It's that simple!
Read More: Java Constructor |
Creating State Object in React
To define the state in a React component, you must first declare a default set of values in the component's constructor. This default state is stored within the this.state object, which holds all the data related to the component’s state.
In React, there are two main approaches to define and manage state:
- Class Components: In class components, the state is initialized within the constructor and updated using the this.setState() method.
- Hooks: With the introduction of React Hooks, managing state has become more convenient in functional components. The useState() hook allows you to declare state variables directly in functional components.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'React'
};
}
render() {
return {this.state.name};
}
}
import React, { useState } from 'react';
const MyComponent = () => {
const [name, setName] = useState('React');
return {name};
}
While both approaches allow you to define and manage state, class components use a more traditional approach, while hooks offer a more modern and simplified way to work with state in functional components. The choice between these two approaches depends on your project’s needs and React version.
Conventions of Using State in React
When working with React, it's important to follow some conventions for using the state of a component. These rules ensure that your components remain efficient and behave as expected.
- The state should persist throughout the component’s lifetime. To achieve this, always define the state in the constructor of the component’s class, ensuring that it has an initial value.
- Never update the state directly. React uses an observable object for the state, which means it keeps track of changes. React’s internal system automatically updates the component whenever the state changes.
- Use setState() to modify the state. The setState() method takes an object as a parameter and expects it to contain the updated values for the state properties. It will then automatically trigger a re-render of the component.
- State updates should be independent. If your component has multiple properties in its state, you can update each one separately. You can use setState() multiple times to update different state attributes without affecting others.
- The only time you should define the state explicitly is when you’re providing the initial values in the constructor.
By following these conventions, you ensure that your components behave predictably and maintain their performance.
Updating State in React
In React, you can update a state object using the setState() method. However, React may batch multiple setState() updates, which can lead to unexpected behavior if you're relying on the current state value during updates.
For example, this approach is incorrect:
this.setState({counter: this.state.count + this.props.diff});
The correct way to update the state, especially when relying on the previous state, is to use a function that takes the previous state and props as parameters:
this.setState((prevState, props) => ({
counter: prevState.count + props.diff
}));
Let's walk through an example where we implement state in React to create a simple counter application:
// Filename - counter.js
import React from "react";
import ReactDOM from "react-dom/client";
class CounterApp extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increaseCount = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
decreaseCount = () => {
this.setState((prevState) => ({
count: prevState.count - 1,
}));
};
render() {
return (
The current count is: {this.state.count}
Increase
Decrease
);
}
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
);
This example demonstrates how the setState() method works to update the state based on previous state values. Each time the buttons are clicked, the count is either increased or decreased, triggering a re-render with the updated value.
Managing Complex State in React
In React class components, state can be more than just simple values like numbers or strings. You can manage complex objects or arrays as part of the state. However, when updating them, it's crucial to avoid directly mutating the state.
Read More: Strings in JavaScript |
Here's the basic syntax for managing complex state:
- Initialize state as an object in the constructor:
- To update the state, use setState() and the spread operator to preserve previous values:
this.state = { objectName: { property1: value1, property2: value2 } };
this.setState((prevState) => ({
objectName: { ...prevState.objectName, updatedProperty: newValue }
}));
By using the spread operator (...), you ensure that the previous state values are preserved while updating only the necessary properties. This avoids direct mutation and ensures that React can manage state updates efficiently.
Stateful vs Stateless Components
In React, components can be classified into two types: stateful components and stateless components.
Feature | Stateful Components | Stateless Components |
Definition | Components that manage their own state and control their data. | Components that don't manage their state and rely only on the props passed to them. |
Trigger Re-render | Can re-render themselves when their state changes. | Render JSX based on the provided props without triggering re-renders independently. |
Implementation | Typically implemented using ES6 classes that extend React.Component . | Often implemented as functional components. |
Usage | Used for complex components requiring state management. | Ideal for simple, presentational components. |
Difference Between State and Props
Both state and props are essential for controlling how React components behave and render. However, there are key differences:
Aspect | Props | State |
Definition | Props (short for properties) are passed down from a parent component to a child component. They are immutable and cannot be changed by the child component. | The state controls a component's internal data and can be modified by the component itself. |
Usage | Allows the parent to customize the child component's behavior and appearance. | Updated through event handlers or methods, triggering a re-render to reflect changes in the UI. |
Scope | Set by the parent component and passed down to child components, enabling communication between components. | Specific to the component that owns it and is not accessible by other components. |
Mutability | Immutable - Props cannot be modified once passed down. | Mutable - State can be updated using setState() . |
Common Mistakes with State in React
When working with state in React, developers often make the following mistakes:
- Direct State Modification: A common error is directly modifying the state using
this.state.propertyName = newValue
. This doesn't trigger a re-render. Always usethis.setState()
to update the state. - Incorrect Use of setState(): Since
setState()
is asynchronous and can batch multiple updates, it's important to use the callback function insetState()
when needing to take action after state updates. - Not Using Functional setState(): For updates based on the previous state, always use the functional form of
setState()
. This ensures that the right state is applied, especially when multiple updates are queued. - Overusing State: Storing too much data in state can make it difficult to manage and result in unnecessary re-renders. It's important to store only the data that is required for component rendering.
Advanced State Management Techniques
For complex state management scenarios, React provides several advanced solutions:
- Using Redux: Redux is a popular state management library for React that centralizes the application’s state in a single store. It simplifies the management of complex state and enables predictable updates.
- Context API: The built-in Context API allows components to share data without passing props through every level of the component tree. It provides a way to create a global state accessible by any component in the app.
- React Hooks: React introduced hooks in version 16.8, which allows functional components to manage state and side effects. Hooks like
useState
,useEffect
, anduseContext
simplify state management and improve readability. For in-depth knowledge on using React hooks, consider enrolling in a specialized React JS Course.
Read More: Redux Middleware |
These modern state management techniques offer increased flexibility and can help manage state in more complex applications.
Best Practices for Working with State
To ensure clean and maintainable code, here are some best practices when working with state in React:
- Keep State Simple: State should remain simple and not contain complex data structures or unnecessary data. Break up the state into smaller, manageable parts if needed.
- Set Initial State in Constructor: Always initialize state in the constructor method. This ensures the state is set up properly before any interactions with the component.
- Use setState() to Update State: Always use
setState()
to update the state. Directly changing the state usingthis.state.propertyName = newValue
will not trigger a re-render. - Avoid Direct State Modification: React's state is immutable. Do not modify the state directly. Instead, create a new object and pass it to
setState()
with the updated values. - Use Functional setState() for Dependent Updates: When updating the state based on the previous state, always use the functional form of
setState()
to ensure the correct state is applied. - Batch setState() Calls: If you need to update multiple state properties, you can batch the
setState()
calls together. React will optimize the updates, making the process more efficient.
Resources for Further Learning and Practice
- Official Redux Documentation: The official Redux documentation is an excellent resource for understanding Redux and React-Redux integration. You can find it in Redux Documentation.
- Online Tutorials and Courses: For more tutorials and courses focused on React and Redux, visit React JS Course and React Certification Training.
Summary
This article explored the concept of State in React and its crucial role in managing dynamic data in your applications. From understanding how React state works in class components to mastering the use of useState
in functional components, you’ve learned the necessary techniques to handle data flow effectively in React. Whether you're a beginner or improving your skills, mastering state management is key to building interactive UIs. Want to dive deeper into React development? Enroll in our ReactJS Certification Training today and level up your React skills!
Looking to improve your frontend development skills for free? Check out these Scholarhat Free Courses:
Test Your Knowledge of State in React!
Q 1: What is the purpose of `useState` in React?
- (a) To manage the component's state
- (b) To fetch data from an API
- (c) To render components
- (d) To handle events
Q 2: What is the initial value of state when using `useState(0)` in React?
- (a) null
- (b) undefined
- (c) 0
- (d) false
Q 3: What does the function returned by `useState` in React do?
- (a) It updates the state value
- (b) It renders the component
- (c) It calls the API
- (d) It triggers the lifecycle methods
Q 4: How can you update the state based on the previous state in React?
- (a) By passing a function to the state updater function
- (b) By calling the state updater function directly
- (c) By using
setState()
- (d) By using
forceUpdate()
Q 5: Which hook should you use to handle state in a class component in React?
- (a) useState
- (b) useEffect
- (c) setState
- (d) useReducer
Take our React skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.