React Context API – Sharing Data Without Props

✅ What is Context API?

React Context API allows you to share data across components without passing props manually through each level.

Think of it like a global variable for a React app — but in a clean, React way.

🤯 Why Use It?

Let’s say you want to share:

  • A logged-in user’s info
  • A theme (light/dark)
  • A language preference
  • A shopping cart

Instead of doing prop drilling:

<App>
  <Navbar user={user}>
    <Sidebar user={user}>
      <Profile user={user} />
    </Sidebar>
  </Navbar>
</App>

You use Context and simply access user anywhere directly.

🏗️ How to Use Context API (Step by Step)

✅ 1. Create the Context

import { createContext } from 'react';

export const UserContext = createContext();

✅ 2. Provide the Context (wrap your app or part of it)

import { useState } from 'react';
import { UserContext } from './UserContext';
import Dashboard from './Dashboard';

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

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

UserContext.Provider makes user and setUser available to all child components

✅ 3. Consume the Context (anywhere below the provider)

import { useContext } from 'react';
import { UserContext } from './UserContext';

function Dashboard() {
  const { user } = useContext(UserContext);

  return <h1>Welcome, {user}!</h1>;
}

✅ 4. Update Context from Child

function ProfileSettings() {
  const { user, setUser } = useContext(UserContext);

  return (
    <div>
      <p>Current user: {user}</p>
      <button onClick={() => setUser("Bob")}>Switch User</button>
    </div>
  );
}

✅ Visual Flow:

App
│
└── UserContext.Provider
    │
    ├── Dashboard  (reads user)
    └── ProfileSettings (reads & updates user)

Scenario 2:

🧠 React Context Made Easy

🔄 Problem:

In a React app, sometimes we want to share data between many components — like:

  • Logged-in user info
  • Theme (light/dark)
  • Language
  • Cart data

But passing this data manually through props to every component becomes messy. This is called “prop drilling.”

🎒 Real-Life Analogy

Imagine your app is like a school:

  • You (parent component) want to give every student (child components) a lunchbox (data).
  • Without context: You give it to the teacher, the teacher gives it to class monitor, and finally to each student.
  • With context: You just put the lunchboxes in a common table (context), and students pick them up directly — no middleman.

✅ React Context Solution: One-Time Setup, Global Access


📦 Full Example: User Context

We’ll create a context that shares the logged-in user’s name with multiple components.

1. Create Context (UserContext.js)

import { createContext } from "react";

// Create context
const UserContext = createContext();

export default UserContext;

2. Provide Context (App.js)

import React, { useState } from "react";
import UserContext from "./UserContext";
import Header from "./Header";
import Profile from "./Profile";

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

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

export default App;

✅ Now any component inside <UserContext.Provider> can access user and setUser without props.

3. Consume Context in Child (Header.js)

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

function Header() {
  const { user } = useContext(UserContext);

  return <h1>Welcome, {user}!</h1>;
}

export default Header;

4. Update Context Value (Profile.js)

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

function Profile() {
  const { user, setUser } = useContext(UserContext);

  return (
    <div>
      <p>Current user: {user}</p>
      <button onClick={() => setUser("Bob")}>Switch to Bob</button>
    </div>
  );
}

export default Profile;

🧪 Output:

  • Header shows: Welcome, Alice!
  • Profile shows: Current user: Alice
  • Click button → user switches to Bob → both components update!

🧩 When to Use React Context?

✅ Use Context when:

  • You need to share data between many components
  • You want to avoid passing props down multiple levels
  • For theme, auth, language, user, cart, etc.

Keep Learning 🙂

Leave a Reply

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