contextapi
contextapi
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)`.
---
Here’s the simplified pattern you can reuse for any context:
---
```js
// CartContext.js
import React, { createContext, useContext, useReducer } from 'react';
return (
<CartContext.Provider value={{ /* state + actions */ }}>
{children}
</CartContext.Provider>
);
};
// ✅ Custom hook
export const useCart = () => {
const context = useContext(CartContext);
if (!context) throw new Error('useCart must be used within a CartProvider');
return context;
};
```
---
```js
// AnyComponent.js
import React from 'react';
import { useCart } from '../context/CartContext';
---
### 🔁 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.)?