React — Context
Creating Context
import { createContext } from 'react';
const ThemeContext = createContext('light');
Providing Context
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<MyComponent />
</ThemeContext.Provider>
);
}
Consuming Context
import { useContext } from 'react';
function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
</button>
);
}
Context Examples
// User context
const UserContext = createContext();
function App() {
const [user, setUser] = useState(null);
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
<UserContext.Provider value={{ user, login, logout }}>
<Router />
</UserContext.Provider>
);
}
function Navbar() {
const { user, logout } = useContext(UserContext);
return (
<nav>
{user ? (
<div>
<span>Welcome, {user.name}</span>
<button onClick={logout}>Logout</button>
</div>
) : (
<a href="/login">Login</a>
)}
</nav>
);
}
// Cart context
const CartContext = createContext();
function CartProvider({ children }) {
const [items, setItems] = useState([]);
const addItem = (item) => {
setItems([...items, item]);
};
const removeItem = (id) => {
setItems(items.filter(item => item.id !== id));
};
const getTotal = () => {
return items.reduce((total, item) => total + item.price, 0);
};
return (
<CartContext.Provider value={{ items, addItem, removeItem, getTotal }}>
{children}
</CartContext.Provider>
);
}
function Cart() {
const { items, removeItem, getTotal } = useContext(CartContext);
return (
<div>
<h2>Cart</h2>
{items.map(item => (
<div key={item.id}>
{item.name} - ${item.price}
<button onClick={() => removeItem(item.id)}>
Remove
</button>
</div>
))}
<p>Total: ${getTotal()}</p>
</div>
);
}
Mini Practice
Write React code that:
- Creates a context
- Provides context value
- Consumes context with useContext
- Creates a context with state
Up Next
Next: Learn about Portals.
Related Topics
Frequently Asked Questions about Context
What is Context in React?
Context is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Context?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Context.
Why is Context important in React?
Context is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.