28
AugState 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?
In ReactJS, state is a built-in object used to store data specific to a component. It plays a crucial role in building dynamic and interactive user interfaces by allowing components to respond to user actions, events, and changes over time.
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 |
Types of State in React JS
React offers different types of state to manage dynamic data based on the component's scope and the nature of the data. Understanding these types helps in building clean, scalable, and high-performing applications.
1. Local State (Component State)
Local state is specific to a single component and is used to store data that affects only that component’s behavior or rendering.
- In functional components, local state is managed using the useState hook.
- In class components, it is managed via this.state and updated using this.setState().
2. Global State
Global state is shared across multiple components, often across different levels of the component hierarchy. It holds data that needs to be accessed and modified by various parts of the application.
- Managed using React Context API or state management libraries like Redux, Zustand, or Jotai, especially in large-scale apps.
3. Server State
Server state represents external data stored on a remote server that needs to be fetched, cached, and kept in sync with the client-side UI.
- It often involves asynchronous operations, such as fetching data from REST APIs or GraphQL endpoints.
- Tools like React Query and SWR help manage server state efficiently with features like caching, background updates, and error handling
4. URL State (Router State)
URL state is the data encoded in the URL itself, such as query parameters or dynamic route segments. It reflects the current view or configuration of the application.
- Managed using routing libraries like React Router, which provides access to route params, search params, and more.
5. Derived State (Computed State)
Derived state is not stored independently, but rather calculated from other existing state or props. It ensures consistency and avoids redundancy in your component logic.
- It's a good practice to compute derived values on the fly instead of storing them in state.
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:
1. Direct State Modification- One of the most frequent mistakes is attempting to modify the state directly, such as assigning a new value to a state property (this.state.property = value). This approach does not trigger a re-render, which means the UI won’t reflect the updated data.
2. Misunderstanding setState() Behavior- setState() is asynchronous and React may batch multiple state updates together to optimize performance. Developers sometimes expect immediate access to the updated state right after calling setState(), which can lead to logical errors.
3. Not Using Functional setState() for Dependent Updates- Another mistake is updating state based on the current state without using the functional form. If multiple updates are queued, using outdated state can cause incorrect values or lost updates.
4. Overusing or Overloading State- Storing too much or unnecessary data in state can make components harder to manage and negatively affect performance. This often leads to excessive re-renders and bloated component logic.
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:
1. Keep State Simple and Minimal- State should be as minimal and straightforward as possible. Avoid storing unnecessary data or creating deeply nested structures within the state. Complex state objects can make your components harder to debug and maintain. Instead, focus on storing only the data that is essential for rendering the UI or handling component behavior. If the state starts to grow too large, consider breaking it into smaller, more manageable parts or using state management libraries like Redux or Context API for better organization.
2. Initialize State Properly in the Component- Always ensure that state is initialized at the beginning of the component’s lifecycle. For class-based components, this typically means setting up the state inside the constructor. For functional components, initialization is done using the useState hook. A well-initialized state provides a predictable structure for your component and prevents errors during the initial render or user interaction. Starting with a clear initial state also makes your component’s logic easier to follow and debug.
3. Always Use React's setState() Method for Updates- Never try to update the state directly. React provides the setState() method (or equivalent hooks like useState() for functional components) for a reason — it ensures that your component knows when to re-render and keeps the UI in sync with your data. Directly modifying the state variable bypasses React’s update process and can lead to unexpected UI behavior, missed updates, and bugs that are hard to trace.
4. Avoid Direct Mutation of State- State in React is designed to be immutable. This means that you should not modify the existing state object or array directly. Instead, always create a new copy of the state with the desired changes and then update it. React uses shallow comparisons to detect changes in state, and direct mutation can cause it to miss updates, leading to parts of the UI not re-rendering as expected. Following immutability principles improves both the reliability and predictability of your application.
5. Use Functional Form of State Updates When Dependent on Previous State- When updating state based on its previous value—such as increasing a count or toggling a boolean—use the functional form of state updates. This approach ensures that your component receives the most recent version of state, even if multiple updates are happening asynchronously or in quick succession. React batches state updates for performance, and relying on the current state directly might not always give the correct result unless you use the functional approach.
6. Batch Related setState() Calls for Better Performance- React automatically batches multiple state updates occurring within the same event cycle to improve performance and reduce unnecessary re-renders. When working with multiple related pieces of state, consider updating them together in a single update cycle. Grouping related changes not only enhances performance but also keeps your component’s logic more organized and easier to follow.
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.