Great!
If you want to implement the **React Context API with a custom hook**, it's
already done in the previous example using this line:
```js
export const useCart = () => useContext(CartContext);
```
This `useCart` function is your **custom context hook** – it allows any component
to easily access the cart state and actions without repeating
`useContext(CartContext)`.
---
## ✅ Breakdown of the Context Hook
Here’s the simplified pattern you can reuse for any context:
---
### 1. ✅ Create Context + Hook
```js
// [Link]
import React, { createContext, useContext, useReducer } from 'react';
const CartContext = createContext();
export const CartProvider = ({ children }) => {
const [state, dispatch] = useReducer(/* reducer logic */);
// Define actions like addToCart, removeFromCart here...
return (
<[Link] value={{ /* state + actions */ }}>
{children}
</[Link]>
);
};
// ✅ Custom hook
export const useCart = () => {
const context = useContext(CartContext);
if (!context) throw new Error('useCart must be used within a CartProvider');
return context;
};
```
---
### 2. ✅ Use the Hook Anywhere
```js
// [Link]
import React from 'react';
import { useCart } from '../context/CartContext';
const AnyComponent = () => {
const { cart, addToCart } = useCart();
return (
<>
<h3>Cart Items: {[Link]}</h3>
<button onClick={() => addToCart({ id: 1, name: 'Item', price: 50
})}>Add</button>
</>
);
};
```
---
### 🔁 Summary
| Feature | Method |
| --------------- | ---------------------------- |
| Get cart state | `const { cart } = useCart()` |
| Add item | `addToCart(item)` |
| Update quantity | `updateCart(id, quantity)` |
| Remove item | `removeFromCart(id)` |
| Clear cart | `clearCart()` |
---
Would you like me to show a **minimal reusable template** you can copy-paste for
any context (like auth, theme, etc.)?