Context API: A React feature that provides a way to pass data through the component tree without having to pass props down manually at every level. It's designed to share data that can be considered "global" for a tree of React components.
Simple shabdon mein: Imagine karo ek joint family hai. Agar dadi ko kuch batana hai pote ko, toh normal tarike se dadi โ papa โ beta โ pota (prop drilling) karna padega. Lekin Context API ek loudspeaker ki tarah hai - dadi seedha announce kar deti hai aur pota sun leta hai! ๐ข
Problem ye solve karta hai: Prop drilling - jab aapko data 5-6 levels neeche bhejni ho toh har component mein props pass karna padta hai, chahe beech wale components ko us data ki zaroorat na ho.
๐ฏ Prop Drilling vs Context API
โ Prop Drilling
App (data)
Parent (props)
Child (props)
GrandChild (use)
Har level pe props pass karna padta hai
โ
โ Context API
Provider (data)
Parent
Child
Consumer (use)
Seedha access, beech wale ko tension nahi
1๏ธโฃ Context Create Karna & Provide Karna
Creating Context: The process of initializing a new context using React.createContext(), which returns a Context object with Provider and Consumer components.
Neeche button click karke theme change karo - ye Context API use kar raha hai!
Current Theme: Light
Ye content theme ke according change hota hai. Context API se har component ko theme ka access mil jata hai bina props pass kiye!
Header Component
Sidebar Component
Footer Component
โ๏ธ Sabhi components ko same theme mil raha hai Context se
2๏ธโฃ useContext Hook - Deep Dive
useContext Hook: A React Hook that lets you read and subscribe to context from your component. It accepts a context object and returns the current context value for that context.
Kaise kaam karta hai? useContext ek subscription ki tarah hai. Jab bhi Provider mein value change hoti hai, sabhi consumers automatically re-render ho jate hain naye value ke saath. Ye real-time sync ki tarah hai!
Re-render Problem: When context value changes, all components consuming that context re-render, even if they only use a small part of the context value. This can cause performance issues in large applications.
Sabse badi problem: Jab Context ki value change hoti hai, toh SABHI components jo us context ko consume kar rahe hain, wo re-render ho jate hain - chahe unko us particular value ki zaroorat ho ya na ho! ๐ฐ
Example: Agar aapke context mein user aur theme dono hain, aur sirf theme change hua, toh bhi wo components re-render honge jo sirf user use kar rahe hain!
๐ฏ Live Demo: Re-render Counter
Dekho kitni baar components re-render ho rahe hain!
Component A
Renders: 0
Uses: user.name
Component B
Renders: 0
Uses: user.age
Component C
Renders: 0
Uses: theme
โ ๏ธ Problem: Sabhi components re-render ho rahe hain, chahe unko us value ki zaroorat na ho!
โ Solutions for Re-render Issues
1. Split Contexts
Alag alag contexts banao different data ke liye
// โ Bad: Ek hi context
<AppContext.Provider
value={{ user, theme,
settings }}>
// โ Good: Alag contexts
<UserContext.Provider>
<ThemeContext.Provider>
<SettingsContext.Provider>
4๏ธโฃ Context API vs Redux - Kab Kya Use Karein?
State Management Comparison: Context API is built into React for sharing data across components, while Redux is a separate library providing a more structured approach to state management with additional features like middleware, time-travel debugging, and strict unidirectional data flow.
Confusion clear karte hain: Context API aur Redux dono state management ke liye hain, lekin dono ka use case alag hai. Context API React ka built-in feature hai, Redux ek external library hai with more features.
Feature
Context API
Redux
Setup Complexity
โ Simple & Quick
โ Complex Boilerplate
Bundle Size
โ 0 KB (Built-in)
โ ~10 KB (External)
DevTools
โ Limited
โ Excellent (Time-travel)
Middleware Support
โ No
โ Yes (Thunk, Saga)
Performance
โ Can cause re-renders
โ Optimized with selectors
Learning Curve
โ Easy
โ Steep
Best For
Small to medium apps, theme, auth
Large apps, complex state logic
โ Use Context API When:
Small to medium sized app
Simple state sharing (theme, language, auth)
Don't want external dependencies
State doesn't change frequently
Quick prototyping
Learning React basics
โ Use Redux When:
Large scale application
Complex state logic & transformations
Need middleware (API calls, logging)
Time-travel debugging required
Multiple developers working
Strict state management patterns needed
Real advice: Agar aapka app chota hai aur sirf theme/auth manage karna hai, toh Context API perfect hai. Lekin agar aapka app bada hai, bahut saari API calls hain, complex state logic hai, toh Redux better choice hai. Don't over-engineer! ๐ฏ
5๏ธโฃ Global Theme Management with Context
Theme Management: A pattern where application-wide styling preferences (colors, fonts, spacing) are stored in context and consumed by all components, enabling features like dark mode, custom themes, and consistent UI across the application.
Real-world use case: Aajkal har app mein dark mode hota hai. Context API se aap ek jagah theme define karo aur puri app mein use karo. User preference save kar sakte ho localStorage mein!
๐ฏ Live Demo: Complete Theme System
Theme Showcase
Ye pura section theme ke according change ho raha hai!
Button
Card
Input
Current Theme:Light
// Complete Theme Context Implementationimport { createContext, useState, useEffect } from'react';
const themes = {
light: {
background: '#ffffff',
text: '#333333',
primary: '#667eea'
},
dark: {
background: '#1e1e1e',
text: '#ffffff',
primary: '#bb86fc'
}
};
export constThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(
localStorage.getItem('theme') || 'light'
);
// Save to localStorage whenever theme changes
useEffect(() => {
localStorage.setItem('theme', theme);
document.body.className = theme;
}, [theme]);
const value = {
theme,
colors: themes[theme],
setTheme
};
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
}
// Custom hook for easy accessexport const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
};
6๏ธโฃ Authentication Management with Context
Auth Context: A pattern for managing user authentication state globally, including login status, user information, tokens, and authentication-related functions accessible throughout the application.
Sabse common use case: User login/logout ka state manage karna. Agar user logged in hai toh dashboard dikhao, nahi toh login page. Context se ye bahut easy ho jata hai - har component ko pata chal jata hai user logged in hai ya nahi!
export const useAuth = () => {
const context =
useContext(AuthContext);
if (!context) {
throw new Error(
'useAuth must be used within AuthProvider'
);
}
return context;
};
2. โ Split Large Contexts
Ek context mein sab kuch mat dalo
// โ Bad
<AppContext value={{
user, theme, settings,
cart, notifications
}}>
// โ Good
<UserContext>
<ThemeContext>
<CartContext>
if (!context) {
throw new Error(
'Component must be wrapped in Provider'
);
}
โ ๏ธ Common Mistakes:
Har choti cheez ke liye context banana (overkill)
Context value ko directly object literal dena (har render pe naya object)
Bahut saare contexts nest karna (provider hell)
Context ko state management library samajhna (it's not Redux!)
๐ฏ Interview Questions (Basic to Advanced)
Click on each question to reveal the answer
Q1. Context API kya hai aur prop drilling problem kaise solve karta hai? (Basic)
โผ
Answer:
Context API: React ka built-in feature hai jo data ko component tree mein share karne ke liye use hota hai bina har level pe props pass kiye.
Prop Drilling Problem:
Jab data ko deeply nested components tak pass karna ho
Beech ke components ko data ki zaroorat nahi hoti but props pass karne padte hain
Code maintenance difficult ho jata hai
Context API Solution:
Provider component se data wrap karo
Koi bhi child component directly access kar sakta hai
Beech ke components ko touch nahi karna padta
Hinglish: Prop drilling matlab data ko 5-6 levels neeche bhejne ke liye har component mein props pass karna. Context API se seedha access mil jata hai, beech wale components ko tension nahi!
Q2. useContext hook kaise kaam karta hai? Consumer component se kya difference hai? (Basic)
โผ
Answer:
useContext Hook:
Modern way to consume context
Functional components mein use hota hai
Clean aur readable syntax
Multiple contexts easily use kar sakte ho
// useContext (Modern)const { user } = useContext(UserContext);
// Consumer (Old way)
<UserContext.Consumer>
{({ user }) => <div>{user.name}</div>}
</UserContext.Consumer>
Differences:
useContext
Consumer
Hook (function)
Component (JSX)
Clean syntax
Nested/verbose
Easy to use multiple
Nesting hell
Q3. Context value change hone pe unnecessary re-renders kaise avoid karein? (Intermediate)
โผ
Answer:
Problem: Jab context value change hoti hai, sabhi consuming components re-render hote hain, chahe unko us particular value ki zaroorat na ho.
Hinglish: Context ko chote chote parts mein todo, value ko memoize karo, aur components ko React.memo se wrap karo. Ye sab techniques combine karke unnecessary re-renders kam kar sakte ho!
Q4. Context API vs Redux - kab kya use karein? Real-world scenarios explain karo (Intermediate)
โผ
Answer:
Context API Use Cases:
Theme Management: Light/dark mode toggle
Authentication: User login state, basic user info
Language/i18n: Multi-language support
UI State: Modal open/close, sidebar toggle
Small Apps: Todo apps, personal projects
Redux Use Cases:
E-commerce: Cart, products, orders, complex state
Social Media: Posts, comments, likes, real-time updates
Hinglish: Choti app hai aur sirf theme/auth chahiye? Context API perfect hai. Badi app hai, bahut saari API calls, complex logic? Redux use karo. Don't over-engineer - start simple!
useMemo: Context value objects, computed values, expensive calculations
useCallback: Functions passed in context, event handlers, API calls
Don't overuse: Simple values (strings, numbers) don't need memoization
Hinglish: Context value mein object ya function pass kar rahe ho? useMemo/useCallback use karo. Warna har render pe naya reference banega aur sabhi components re-render honge. But simple values ke liye over-optimize mat karo!
Q7. Context API ke saath TypeScript use karte waqt type safety kaise ensure karein? (Expert)
โผ