Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Consuming context is like connecting to a data pipeline - components can tap into the context stream and access the data they need without receiving it through props.
First, import the useContext hook from React. This is the modern way to consume context in function components.
Best Practice
Always import useContext at the top of your component file.
Import the context you want to consume. This could be from a separate file or defined in the same file.
Why Import Context?
You need the context object to tell useContext which context value to access.
Call useContext with your context object to access the current context value.
Use the context value in your component's JSX or logic. The value will update automatically when the context changes.
A practical example of consuming shopping cart context with add, remove, and update functionality
// Step 1: Create Shopping Cart Context
const CartContext = React.createContext({
items: [],
total: 0,
addItem: () => {},
removeItem: () => {},
updateQuantity: () => {},
clearCart: () => {}
});
// Step 2: Cart Provider Component
function CartProvider({ children }) {
const [items, setItems] = React.useState([]);
const addItem = (product) => {
setItems(prevItems => {
const existingItem = prevItems.find(item => item.id === product.id);
if (existingItem) {
return prevItems.map(item =>
item.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
);
}
return [...prevItems, { ...product, quantity: 1 }];
});
};
const removeItem = (productId) => {
setItems(prevItems => prevItems.filter(item => item.id !== productId));
};
const updateQuantity = (productId, quantity) => {
if (quantity <= 0) {
removeItem(productId);
return;
}
setItems(prevItems =>
prevItems.map(item =>
item.id === productId
? { ...item, quantity }
: item
)
);
};
const clearCart = () => {
setItems([]);
};
const total = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
const value = {
items,
total,
addItem,
removeItem,
updateQuantity,
clearCart
};
return (
<CartContext.Provider value={value}>
{children}
</CartContext.Provider>
);
}
// Step 3: Custom Hook for cart consumption
function useCart() {
const context = React.useContext(CartContext);
if (!context) {
throw new Error('useCart must be used within a CartProvider');
}
return context;
}
// Step 4: Product Component
function Product(props) {
const { addItem } = useCart();
const id = props.id;
const name = props.name;
const priceValue = props.price || 0;
return (
<div className="product">
<h3>{name}</h3>
<p className="price">${priceValue ? priceValue.toFixed(2) : '0.00'}</p>
<button onClick={() => addItem({ id, name, price: priceValue })} className="add-btn">
Add to Cart
</button>
</div>
);
}
// Step 5: Cart Item Component
function CartItem(props) {
const item = props.item;
const { updateQuantity, removeItem } = useCart();
return (
<div className="cart-item">
<div className="item-info">
<span className="item-name">{item.name}</span>
<span className="item-price">${item.price ? item.price.toFixed(2) : '0.00'}</span>
</div>
<div className="item-controls">
<button
onClick={() => updateQuantity(item.id, item.quantity - 1)}
className="quantity-btn"
>
-
</button>
<span className="quantity">{item.quantity}</span>
<button
onClick={() => updateQuantity(item.id, item.quantity + 1)}
className="quantity-btn"
>
+
</button>
<button
onClick={() => removeItem(item.id)}
className="remove-btn"
>
🗑️
</button>
</div>
</div>
);
}
// Step 6: Cart Component
function Cart() {
const { items, total, clearCart } = useCart();
return (
<div className="cart">
<h2>Shopping Cart</h2>
{items.length === 0 ? (
<p className="empty-cart">Your cart is empty</p>
) : (
<>
{items.map(item => (
<CartItem key={item.id} item={item} />
))}
<div className="cart-summary">
<div className="total">Total: ${total.toFixed(2)}</div>
<button onClick={clearCart} className="clear-btn">
Clear Cart
</button>
</div>
</>
)}
</div>
);
}
// Step 7: Product List Component
function ProductList() {
const products = [
{ id: 1, name: 'Laptop', price: 999.99 },
{ id: 2, name: 'Mouse', price: 29.99 },
{ id: 3, name: 'Keyboard', price: 79.99 },
{ id: 4, name: 'Monitor', price: 299.99 }
];
return (
<div className="product-list">
<h2>Products</h2>
<div className="products-grid">
{products.map(product => (
<Product key={product.id} {...product} />
))}
</div>
</div>
);
}
// Step 8: Root App Component
function App() {
return (
<CartProvider>
<div className="app">
<header className="header">
<h1>🛒 Shopping Cart Demo</h1>
</header>
<main className="main">
<ProductList />
<Cart />
</main>
</div>
</CartProvider>
);
}
// ReactDOM integration
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);Loading preview...