Context API

Subject: React

πŸ” What is Context API?

The Context API is a built-in feature in React that allows you to create global data (like user info, theme, language) and share it across any component in your app β€” without manually passing props through every level.

It solves the problem of prop drilling, where props are passed from parent to child to sub-child unnecessarily.


🎯 When to Use Context API

Use Context when:

  • You have data that needs to be accessible by many components
  • You want to avoid passing props through multiple levels
  • You’re building themes, user auth, language settings, etc.

🧠 Common Use Cases

Use CaseExample
AuthenticationLogged-in user info
ThemingDark/Light mode switch
LanguageMulti-language translation
Cart/CheckoutStore selected items globally

🧱 Context API Structure

The Context API follows 3 simple steps:

  1. Create the context
  2. Provide the context
  3. Consume the context

βœ… Step-by-Step Example: User Context

πŸ”Ή Step 1: Create Context

πŸ”Ή Step 2: Provide Context (Top-Level)

πŸ”Ή Step 3: Consume Context (Any Child)


πŸ”„ How Data Flows

No need to pass props down manually through each layer.


πŸ“Œ Summary Table

ConceptRole
createContext()Creates the context object
ProviderMakes context data available to children
useContext()Hook to access context inside any child component
Global AccessEliminates the need for prop drilling

βœ… Bonus: Update Context Dynamically

Wrap context value as an object:

Now in any component:


⚠️ Limitations of Context API

⚠️ CautionπŸ’‘ Solution
Frequent updates re-render all consumersUse memoization or split your context
Not suited for all global state needsUse state libraries like Redux/Zustand

🧠 Real-Life Analogy

Context is like a shared notice board:

  • Provider = The person who writes the note
  • Consumer = Anyone walking by can read it

No need to hand notes one by one β€” just read from the board!

Perfect for themes, user info, or app-wide settings.