Chapter 11React Tutorial~1 min read
Context API
Context — Global State, Prop Drilling solve
Context API म्हणजे React चा built-in global state solution. Prop drilling (A→B→C→D ला data पाठवणे) टाळायला Context वापरतात. Theme, Auth, Language — या globally needed data साठी perfect आहे.
Marathi Analogy
Context म्हणजे WhatsApp Group Broadcast सारखे! एका जागी message टाक — सगळ्या members ला (components) मिळतो. Props म्हणजे एकाकडून दुसऱ्याकडे manually forward करणे — Context म्हणजे direct broadcast!
Prop Drilling Problem
Problem — props खूप levels खाली पाठवणे
jsx
// ❌ Prop Drilling — कंटाळवाणे आणि fragile
function App() {
const [user, setUser] = useState({ name: "Rahul" });
return <Dashboard user={user} />; // Dashboard ला नको पण pass करावे
}
function Dashboard({ user }) {
return <Sidebar user={user} />; // Sidebar ला नको पण pass करावे
}
function Sidebar({ user }) {
return <UserProfile user={user} />; // अखेर येथे वापरतात
}
function UserProfile({ user }) {
return <h2>Hello {user.name}</h2>;
}Context Solution
createContext + useContext
jsx
import { createContext, useContext, useState } from 'react';
// 1. Context बनवणे — file च्या बाहेर
const UserContext = createContext(null);
// 2. Provider — data wrap करतो
function App() {
const [user, setUser] = useState({ name: "Rahul", city: "Pune" });
return (
// React 19 — .Provider ऐवजी directly Context वापरतात
<UserContext value={user}>
<Dashboard />
</UserContext>
);
}
// 3. Consumer — useContext वापरून data घेतात
function Dashboard() {
return <Sidebar />; // props pass नाही!
}
function Sidebar() {
return <UserProfile />; // props pass नाही!
}
function UserProfile() {
const user = useContext(UserContext); // directly data मिळतो!
return <h2>Hello {user.name} from {user.city}</h2>;
}Theme Context — Real Example
Dark/Light theme toggle
jsx
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext("light");
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
function toggleTheme() {
setTheme(t => t === "light" ? "dark" : "light");
}
return (
<ThemeContext value={theme}>
{/* Extra value — toggle function पण pass करायला */}
{children}
<button onClick={toggleTheme}>
{theme === "light" ? "🌙 Dark" : "☀️ Light"}
</button>
</ThemeContext>
);
}
export function ThemedBox() {
const theme = useContext(ThemeContext);
return (
<div style={{
background: theme === "dark" ? "#333" : "#fff",
color: theme === "dark" ? "#fff" : "#333",
padding: "1rem"
}}>
Current theme: {theme}
</div>
);
}✅ Key Points — लक्षात ठेवा
- ▸createContext(default) — context object बनवतो
- ▸<Context value={data}> — provider wraps children
- ▸useContext(Context) — value consume करतो
- ▸Prop drilling avoid — deeply nested components direct access
- ▸Theme, Auth, Language — global state साठी best
0/12 chapters पूर्ण