React  

State Management in React using Context API

Introduction

Managing global state in React applications can become complex as your app grows. Passing data through multiple components (also known as prop drilling) makes the code harder to maintain and understand.

React Context API provides a clean and efficient way to share data globally without passing props manually at every level.

In this guide, we will understand how Context API works and how to use it effectively with real-world examples.

What is Context API?

Context API is a built-in React feature that allows you to share state across components without prop drilling.

Real-world analogy: Think of Context API like a central storage (like a Wi-Fi router). Any component can connect and access the data without needing wires (props) from every parent.

When to Use Context API

  • User authentication (logged-in user)

  • Theme (dark/light mode)

  • Language preferences

  • Global settings

Create Context

First, create a context:

import { createContext } from "react";

export const AppContext = createContext();

Create Provider

The Provider wraps your application and shares the state globally.

import { useState } from "react";
import { AppContext } from "./AppContext";

export function AppProvider({ children }) {
  const [user, setUser] = useState(null);

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

Wrap Your App

Wrap your root component with the provider:

import { AppProvider } from "./AppProvider";

function App() {
  return (
    <AppProvider>
      <YourRoutes />
    </AppProvider>
  );
}

Consume Context

Now you can access the global state anywhere:

import { useContext } from "react";
import { AppContext } from "./AppContext";

function Profile() {
  const { user } = useContext(AppContext);

  return <div>{user?.name}</div>;
}

Update State from Any Component

function Login() {
  const { setUser } = useContext(AppContext);

  const handleLogin = () => {
    setUser({ name: "John Doe" });
  };

  return <button onClick={handleLogin}>Login</button>;
}

Step-by-Step Flow

  1. Create a Context

  2. Wrap your app with Provider

  3. Store global state inside Provider

  4. Use useContext to access state

  5. Update state from any component

Real-World Example

Imagine an e-commerce app:

  • Without Context: Pass user data through Navbar → Layout → Pages → Components

  • With Context: Any component directly accesses user data

Result: Cleaner code and better scalability

Advantages of Context API

  • Eliminates prop drilling

  • Built into React (no extra libraries)

  • Simple and easy to implement

  • Great for small to medium apps

Disadvantages

  • Not ideal for very large applications

  • Can cause unnecessary re-renders if not optimized

  • Limited compared to advanced libraries like Redux

Best Practices

  • Keep context small and focused

  • Avoid storing frequently changing data

  • Split multiple contexts (AuthContext, ThemeContext)

  • Use memoization to optimize performance

Context API vs Redux

  • Context API: Simple, lightweight, built-in

  • Redux: Powerful, scalable, better for complex state logic

Conclusion

Context API is a powerful and simple solution for managing global state in React applications. It is perfect for handling user data, themes, and other shared states without adding complexity.

Start using Context API in your projects to write cleaner and more maintainable React code.