Module 7 – Context API
1. What is Context API?
Context API is a built-in React feature that allows you to share data between multiple
components without passing props manually through every level.
Simple Definition
> Context API is a way to share global data across the application without prop drilling.
---
Why Do We Need Context API?
Imagine you have a logged-in user.
Many components need user information:
Navbar
Dashboard
Profile
Settings
Sidebar
Without Context API, you'll have to pass the same data through many intermediate
components.
---
Real-Life Example
Imagine a school 🏫.
The Principal announces:
> "Tomorrow is a holiday."
Every class receives the same announcement.
The Principal doesn't tell each student individually.
Similarly, Context API shares data with all required components at once.
---
What is Prop Drilling?
Prop Drilling means passing props through multiple intermediate components, even if those
components don't use the data.
Example:
App
↓
Dashboard
↓
Sidebar
↓
Profile
↓
User
If only the User component needs the data, every component above must still receive and pass
the props.
This makes the code:
❌ Longer
❌ Harder to maintain
❌ Difficult to debug
---
Solution: Context API
Instead of passing props through every component:
App
↓
Context Provider
↓
Any Component
Any component can access the data directly.
---
Real-Life Example
Think about Wi-Fi 📶.
Without Wi-Fi:
You connect each device separately using cables.
With Wi-Fi:
Every device connects directly to the router.
Context API works like Wi-Fi for your React data.
---
Creating Context
Create a new file:
src/context/[Link]
import { createContext } from "react";
const UserContext = createContext();
export default UserContext;
---
What is createContext()?
createContext() creates a global data container.
Think of it as an empty box that will later store data.
---
Provider
The Provider shares data with the entire application.
Example:
import UserContext from "./UserContext";
function App(){
return(
<[Link] value={"Swasti"}>
<Home/>
</[Link]>
);
Here:
value = "Swasti"
is shared globally.
---
Consumer
The component that receives data is called the Consumer.
Nowadays, instead of <Consumer>, we mostly use the useContext Hook.
---
useContext()
Syntax
import { useContext } from "react";
const value = useContext(UserContext);
---
Example
import { useContext } from "react";
import UserContext from "./UserContext";
function Profile(){
const user = useContext(UserContext);
return <h2>Welcome {user}</h2>;
Output:
Welcome Swasti
---
Complete Flow
createContext()
↓
Provider
value
useContext()
Any Component
---
Passing Objects
Instead of passing only strings, we can pass objects.
const user = {
name: "Swasti",
age: 22,
course: "MCA"
};
<[Link] value={user}>
Using it:
const user = useContext(UserContext);
return(
<>
<h2>{[Link]}</h2>
<h2>{[Link]}</h2>
</>
);
---
Passing Functions
Context can also share functions.
Example:
const login = ()=>{
[Link]("Logged In");
<[Link]
value={{login}}
>
Using it:
const {login} = useContext(UserContext);
<button onClick={login}>
Login
</button>
---
Theme Example
Imagine a website has:
Light Mode
Dark Mode
Instead of sending theme props to every component,
Context API shares the theme globally.
ThemeContext
Navbar
Sidebar
Dashboard
Footer
---
Authentication Example
User logs in once.
The following components need user information:
Navbar
Dashboard
Profile
Orders
Cart
Context API shares login details with all of them.
---
Shopping Cart Example
Cart Items:
Laptop
Phone
Mouse
Every page needs cart information.
Instead of passing props everywhere,
Context API provides it globally.
---
Multiple Contexts
Large applications often have multiple contexts.
Example:
ThemeContext
UserContext
CartContext
LanguageContext
Each context handles a different type of data.
---
Folder Structure
src/
context/
[Link]
[Link]
[Link]
components/
pages/
---
Context API vs Props
Props Context API
Parent → Child Global Data
Manual Passing Direct Access
Good for small apps Best for medium/large apps
Can cause Prop Drilling Eliminates Prop Drilling
---
Context API vs Redux
Context API Redux
Built into React External Library
Easy to Learn More Complex
Best for medium appsBest for large apps
Less Boilerplate More Boilerplate
Simple Global State Advanced State Management
---
Best Practices
✅ Create separate context files.
✅ Use useContext() instead of <Consumer>.
✅ Keep context focused on one responsibility (User, Theme, Cart).
✅ Avoid storing every piece of state in one context.
---
Common Mistakes
❌ Forgetting to wrap components with the Provider.
❌ Using useContext() outside the Provider.
❌ Putting too much unrelated data into one context.
❌ Creating unnecessary contexts.
---
Practical Task
Build a Theme Switcher.
Requirements:
Light Theme
Dark Theme
Use Context API
Theme changes across all components without props.
---
Assignment
Create a Student Portal.
Features:
Login
Logout
User Name
Course
Theme Switch
Profile Page
Dashboard
Navbar
Use Context API to manage:
User Data
Theme
Login Status
---
Interview Questions
1. What is Context API?
2. Why do we use Context API?
3. What is Prop Drilling?
4. How does Context API solve Prop Drilling?
5. What is createContext()?
6. What is a Provider?
7. What is a Consumer?
8. What is useContext()?
9. Can Context API share functions?
10. Can Context API store objects?
11. Difference between Props and Context API?
12. Difference between Context API and Redux?
13. Can we create multiple contexts?
14. What happens if useContext() is used outside a Provider?
15. When should you use Context API instead of Props?
---
Mini Project – E-Commerce Global State Management
Features
User Login
Logout
Theme Toggle
Shopping Cart
Wishlist
User Profile
Navbar with Cart Count
Product Details
Order Summary
Contexts
UserContext → User authentication
ThemeContext → Light/Dark mode
CartContext → Cart items and total count
Concepts Covered
createContext()
Provider
useContext()
Global State Management
Prop Drilling Solution
Multiple Contexts
Authentication
Theme Management
Cart Management
---
💡 Internship Tip for Students
A common interview question is:
> "When should I use Props, Context API, and Redux?"
A simple answer is:
Props → Pass data between closely related components (Parent → Child).
Context API → Share common data like user, theme, or language across many components.
Redux → Manage complex global state in large applications with many independent data
updates.
_____________________________________