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 Case | Example |
---|---|
Authentication | Logged-in user info |
Theming | Dark/Light mode switch |
Language | Multi-language translation |
Cart/Checkout | Store selected items globally |
π§± Context API Structure
The Context API follows 3 simple steps:
- Create the context
- Provide the context
- 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
Concept | Role |
---|---|
createContext() | Creates the context object |
Provider | Makes context data available to children |
useContext() | Hook to access context inside any child component |
Global Access | Eliminates 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 consumers | Use memoization or split your context |
Not suited for all global state needs | Use 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.
Advertisement Slot 1
Advertisement Slot 2