Contact Us : +91 90331 80795

Blog Details

Breadcrub
Blog Detail

Understanding Different States in React: A Beginner-Friendly Guide

State management is one of the most important concepts in React. It plays a key role in building apps that are interactive and dynamic. Whether you are just starting out or already experienced in React, understanding the different kinds of states can help you write cleaner, more efficient code. This guide will explain each type of state, its uses, and how to manage it step by step in simple language.
 

What is State in React?

 
In React, a state is an object that holds information about a component. This information decides how the component behaves and what it looks like.
 
When a state changes, React updates (or re-renders) the component to show the new information.
 
For example:
 
  • A state might hold the number of times a button is clicked.

  • When the button is clicked, the state changes and React updates the button's display to show the new count.

In a real React application, different types of states are used based on the complexity of the app. Let's explore these types.
 
 

1. Local State

 
Local state is data that belongs to a single component. It’s perfect for handling small tasks like:
 
  • Managing form inputs (e.g., text fields, checkboxes).

  • Showing or hiding elements (like modals or tooltips).

  • Switching between light and dark themes.
 
How to Use Local State
React provides a built-in function called useState to manage the local state.

Here’s an example:

import React, { useState } from 'react';  

function Counter() {  
  const [count, setCount] = useState(0); // Initialize state with 0  

  return (  
    <div>  
      <p>Count: {count}</p>  
      <button onClick={() => setCount(count + 1)}>Increment</button>  
    </div>  
  );  
}  
 
Explanation
 
  • useState is used to create a state variable called count.

  • setCount is the function used to update the state.

  • When the button is clicked, setCount increases the value of count by 1.
When to Use Local State
 
  • Handling user input in forms.

  • Toggling the visibility of UI elements.

  • Keeping track of simple component-specific values.
 

2. Global State

 
Global state is shared across multiple components in your app. It’s commonly used for:
 
  • User login information (e.g., checking if the user is logged in).

  • App-wide themes (like dark mode or light mode).

  • Data fetched from an API that needs to be accessible in multiple components.
 
How to Manage Global State
React doesn’t have a built-in solution for a global state. You’ll need tools like:
 
  • Context API (a React feature).

  • Redux (a state management library).

  • Zustand (a lightweight library).
Here’s how you can use the Context API to manage the global state:
import React, { createContext, useContext, useState } from 'react';  

// Create a Context  
const UserContext = createContext();  

function App() {  
  const [user, setUser] = useState({ name: "John Doe" });  

  return (  
    <UserContext.Provider value={{ user, setUser }}>  
      <Profile />  
    </UserContext.Provider>  
  );  
}  

function Profile() {  
  const { user } = useContext(UserContext); // Access global state  
  return <p>Welcome, {user.name}!</p>;  
}  
 
Explanation
 
  • The UserContext is used to share the user state across multiple components.

  • The Profile component can access and display the user data without passing it as a prop.

When to Use Global State
 
  • Managing user authentication (e.g., login/logout).

  • App-wide settings (e.g., themes, language).

  • Sharing data between unrelated components.
 

3. Server State

 
The server state comes from external sources like APIs or databases. It’s often used when your app needs to:
 
  • Fetch data from a server.

  • Sync data between the front end and back end.

  • Cache frequently used data.
 
How to Manage Server State
You can use tools like
 
  • React Query: Simplifies server state management.

  • Axios or Fetch API: Handles HTTP requests manually.

 
Here’s an example using React Query:
import { useQuery } from 'react-query';  

function Users() {  
  const { data, isLoading, error } = useQuery('users', () =>  
    fetch('/api/users').then(res => res.json())  
  );  

  if (isLoading) return <p>Loading...</p>;  
  if (error) return <p>Error loading data</p>;  

  return (  
    <ul>  
      {data.map(user => (  
        <li key={user.id}>{user.name}</li>  
      ))}  
    </ul>  
  );  
}  
 
Explanation

  • useQuery fetches data and handles loading or error states automatically.
When to Use Server State
 
  • Fetching user information, product listings, or posts from an API.

  • Keeping local data updated with server changes.

 

4. Derived State

 
Derived state is not stored but calculated based on existing state or props.
 
For example, if you have a list of items and need to calculate their total price, you can compute it dynamically.
 
How to Use Derived State
Here’s an example:
function ShoppingCart({ items }) {  
  const total = items.reduce((sum, item) => sum + item.price, 0);  

  return <p>Total Price: ${total}</p>;  
}  
 
Explanation

  • The total value is calculated every time the items array changes.
When to Use Derived State
 
  • Summarizing data (e.g., totals, averages).

  • Transforming or filtering data before display.

 

5. UI State

 
UI state is used to control user interface elements like:
 
  • Showing or hiding modals, dropdowns, or tooltips.

  • Managing loading spinners or progress bars.

 
How to Manage UI State
Here’s an example:
function Modal() {  
  const [isOpen, setIsOpen] = useState(false);  

  return (  
    <div>  
      <button onClick={() => setIsOpen(true)}>Open Modal</button>  
      {isOpen && (  
        <div className="modal">  
          <p>This is a modal</p>  
          <button onClick={() => setIsOpen(false)}>Close</button>  
        </div>  
      )}  
    </div>  
  );  
}  
 
When to Use UI State
 
  • Modals and popups.

  • Controlling dropdown menus.

  • Displaying loading indicators.
 

6. Session State


The session state is temporary and only lasts while the user is using the app. It’s often used for:
 
  • Shopping carts.
  • Storing temporary preferences.

How to Manage Session State
Here’s an example using sessionStorage:
function useSessionStorage(key, initialValue) {  
  const [value, setValue] = useState(() => {  
    const saved = sessionStorage.getItem(key);  
    return saved ? JSON.parse(saved) : initialValue;  
  });  

  const save = (newValue) => {  
    setValue(newValue);  
    sessionStorage.setItem(key, JSON.stringify(newValue));  
  };  

  return [value, save];  
}  

 

Choosing the Right State

 
Local State: For single components.
 
Global State: For app-wide data.
 
Server State: For fetching and syncing data.
 
Derived State: For computed values.
 
UI State: For managing UI elements.
 
Session State: For temporary user data.
 
 

Sparkle Web Can Support

At Sparkle Web, we specialize in building React apps with efficient state management. Whether it’s local state for small components or global state for large systems, we can help you create apps that are fast, reliable, and easy to maintain.

Contact us today to start your next project!

    Author

    • Owner

      Vikas Mishra

      A highly skilled Angular & React Js Developer. Committed to delivering efficient, high-quality solutions by simplifying complex projects with technical expertise and innovative thinking.

    Contact Us

    Free Consultation - Discover IT Solutions For Your Business

    Unlock the full potential of your business with our free consultation. Our expert team will assess your IT needs, recommend tailored solutions, and chart a path to success. Book your consultation now and take the first step towards empowering your business with cutting-edge technology.

    • Confirmation of appointment details
    • Research and preparation by the IT services company
    • Needs assessment for tailored solutions
    • Presentation of proposed solutions
    • Project execution and ongoing support
    • Follow-up to evaluate effectiveness and satisfaction

    • Email: info@sparkleweb.in
    • Phone Number:+91 90331 80795
    • Address: 303 Capital Square, Near Parvat Patiya, Godadara Naher Rd, Surat, Gujarat 395010