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

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:

Result: Cleaner code and better scalability

Advantages of Context API

Disadvantages

Best Practices

Context API vs Redux

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.