Skip to main content

Command Palette

Search for a command to run...

React Context API

Updated
β€’5 min read

πŸš€ What is Context API?

The Context API is a built-in React feature that allows you to share data globally across components without passing props manually at every level.

πŸ‘‰ It solves the problem of prop drilling.


πŸ”₯ What is Prop Drilling?

Prop drilling happens when you pass data through multiple intermediate components:

<App user={user}>
  <Parent user={user}>
    <Child user={user}>
      <DeepChild user={user} />
    </Child>
  </Parent>
</App>

❌ Problems:

  • Boilerplate code

  • Hard to maintain

  • Unnecessary dependencies


βœ… Context API Solution

Instead of passing props manually, Context lets you:

πŸ‘‰ β€œBroadcast data to any component that needs it”


βš™οΈ How Context API Works (Core Concepts)

There are 3 main parts:


1. createContext()

Creates a context object

const MyContext = React.createContext();

2. Provider (Source of Data)

Wrap components with a provider

<MyContext.Provider value={data}>
  <App />
</MyContext.Provider>

3. Consumer (Access Data)

Use useContext hook

const value = useContext(MyContext);

βœ… Step-by-Step Practical Example

🎯 Use Case: User Authentication


1. Create Context

import { createContext } from "react";

export const AuthContext = createContext();

2. Provide Data (Top Level)

import React, { useState } from "react";
import { AuthContext } from "./AuthContext";

function App() {
  const [user, setUser] = useState("Pushpesh");

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

3. Consume Data Anywhere

import React, { useContext } from "react";
import { AuthContext } from "./AuthContext";

function Dashboard() {
  const { user, setUser } = useContext(AuthContext);

  return (
    <>
      <h1>Welcome {user}</h1>
      <button onClick={() => setUser("Admin")}>
        Switch User
      </button>
    </>
  );
}

βœ… What Just Happened?

  • App holds global state

  • Dashboard accesses it directly

  • No props needed βœ…


🧩 Best Practices (VERY IMPORTANT)


βœ… 1. Keep Context Focused

❌ Bad (everything in one context)

<AppContext value={{ user, theme, cart, settings }}>

βœ… Good (split contexts)

<AuthContext />
<ThemeContext />
<CartContext />

βœ… 2. Wrap Logic in Custom Hooks

πŸ‘‰ Cleaner and reusable

export const useAuth = () => {
  return useContext(AuthContext);
};

Usage:

const { user } = useAuth();

βœ… 3. Keep Heavy Logic Outside Context

Context should:

  • ❌ NOT contain complex reducers/business logic

  • βœ… ONLY share state


βœ… 4. Avoid Frequent Updates

πŸ‘‰ Context re-renders all consumers

So avoid putting:

  • rapidly changing data (e.g., typing input)

⚠️ Limitations of Context API

This is where many developers misuse it.


❌ 1. Performance Issues

Whenever context value changes:

πŸ‘‰ ALL components using it re-render

Even if they don’t need the update.


❌ 2. Not Ideal for Complex State

If your app has:

  • Multiple state slices

  • Nested logic

  • Async operations

Context becomes messy


❌ 3. Hard to Scale

Large apps become:

  • Hard to debug

  • Hard to track data flow


πŸ†š When NOT to Use Context β†’ Use Redux Toolkit


🚫 Avoid Context if:

❌ 1. Large Global State

Example:

  • E-commerce app

  • Dashboard with many modules


❌ 2. Complex State Logic

Example:

  • Multiple reducers

  • Derived state

  • Async API calls


❌ 3. Frequent Updates

Example:

  • Real-time data

  • Animations

  • Typing input shared globally


❌ 4. Need Dev Tools & Debugging

Context:

  • No built-in debugging

Redux Toolkit:

  • DevTools support βœ…

βœ… When to Use Redux Toolkit Instead

Redux Toolkit is better when:


βœ… 1. App is Large & Scalable

  • Many features connected together

βœ… 2. Complex Business Logic

Example:

  • Cart system

  • Order flow


βœ… 3. Async Operations

Redux Toolkit has:

  • createAsyncThunk

βœ… 4. Predictable State Management

Redux ensures:

  • Centralized store

  • Clear state transitions


βš–οΈ Context API vs Redux Toolkit

Feature Context API Redux Toolkit
Setup Simple Moderate
Best For Small/global data Large apps
Performance Can re-render often Optimized
Debugging Basic DevTools βœ…
Async handling Manual Built-in βœ…
Scalability Limited High

🧭 Real Developer Decision Guide


βœ… Use Context API When:

  • Auth user data

  • Theme (dark/light)

  • Language settings

  • App-level config


βœ… Use Redux Toolkit When:

  • Complex workflows

  • Many interconnected states

  • Global state with logic

  • API-heavy apps


🧠 Final Mental Model

Think like this:


πŸ“‘ Context API = WiFi Router

  • Broadcast data

  • Simple usage

  • No control over who uses what


🏦 Redux Toolkit = Bank System

  • Structured

  • Secure

  • Controlled updates

  • Full transaction history


πŸš€ Final Takeaway

Use Context API for simple shared state, but switch to Redux Toolkit when your app grows in complexity, scale, and logic.