🧠 What is Context API?


⚙️ Basic Flow

  1. Create a Context
  2. Provide the Context to your component tree
  3. Consume the Context in any component that needs the data

🧩 Step-by-Step Example

1️⃣ Create Context

import React, { createContext } from "react";
export const UserContext = createContext();

2️⃣ Provide Context

function App() {
  const user = { name: "Alice", age: 25 };
  
  return (
    <UserContext.Provider value={user}>
      <Home />
    </UserContext.Provider>
  );
}

3️⃣ Consume Context

You can consume it two ways:

A. Using useContext hook (preferred way)

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

function Home() {
  const user = useContext(UserContext);
  return <h2>Welcome, {user.name}!</h2>;
}

B. Using Context Consumer

<UserContext.Consumer>
  {(user) => <h2>Hello, {user.name}</h2>}
</UserContext.Consumer>

🔍 When to Use Context