Chapter 15: Context API & State Management

Today we’ll learn how to use React’s built-in Context API to share state deeply in the component tree without passing props everywhere.

We’ll go very slowly and clearly, like I’m sitting next to you in Mumbai with our laptops open, chai on the table, and I’m explaining everything live with complete, copy-paste-ready examples.

1. When to Use Context (and When NOT to)

Use Context when:

  • You have global or shared data that many components (at different levels) need to access
  • Examples:
    • Current theme (light/dark)
    • Authenticated user info
    • Language/locale settings
    • Cart contents in an e-commerce app
    • App-wide settings (font size, accessibility preferences)

Do NOT use Context when:

  • The data is only needed by one or two close components → use props or lift state up
  • You’re dealing with very frequent updates (like mouse position) → Context can cause unnecessary re-renders
  • You need very complex state logic → better to use Zustand, Jotai, or Redux Toolkit (we’ll cover later)

Golden Rule (2026 best practice): Context is perfect for low-frequency, global data that needs to be accessed by many nested components.

2. Creating & Providing Context (Step by Step)

Let’s build a real-world Theme Switcher that works across the entire app.

Step 1: Create the Context

Create src/context/ThemeContext.tsx

tsx

Step 2: Wrap Your App with the Provider

In src/main.tsx:

tsx

Now every component in your app can access the theme!

Step 3: Consume Context with useContext (or our custom hook)

Create a component deep in the tree: src/components/ThemedButton.tsx

tsx

Now you can drop <ThemedButton /> anywhere in your app — even 10 levels deep — and it will work!

3. Full Example: Complete Theme + User Auth Context

Let’s make it more realistic — combine theme and user authentication.

Create src/context/AppContext.tsx

tsx

Wrap in main.tsx:

tsx

Now use it anywhere:

src/components/ProfileCard.tsx

tsx

4. Avoiding Prop Drilling – Before & After

Before Context (prop drilling hell):

tsx

After Context:

tsx

Summary – Chapter 15 Key Takeaways

  • Context = share state deeply without prop drilling
  • Create context with createContext
  • Provide value with <Provider>
  • Consume with useContext (or custom hook like useTheme)
  • Use custom provider + hook pattern → clean & safe
  • Perfect for global, low-frequency data (theme, auth, settings)
  • For very complex/global state → consider Zustand or Jotai later

Mini Homework

  1. Create an AuthContext with login/logout + current user
  2. Make a Navbar that shows “Login” or “Welcome, Webliance!” + Logout button
  3. Make a ProtectedRoute that redirects to login if not authenticated

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *