0% found this document useful (0 votes)
3 views

contextapi

The document explains how to implement the React Context API with a custom hook, specifically for managing a cart state. It provides a breakdown of creating a context and a custom hook, `useCart`, which allows components to access cart state and actions easily. Additionally, it includes a summary of features and methods available for interacting with the cart.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

contextapi

The document explains how to implement the React Context API with a custom hook, specifically for managing a cart state. It provides a breakdown of creating a context and a custom hook, `useCart`, which allows components to access cart state and actions easily. Additionally, it includes a summary of features and methods available for interacting with the cart.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

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
// CartContext.js
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 (
<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;
};
```

---

### 2. ✅ Use the Hook Anywhere

```js
// AnyComponent.js
import React from 'react';
import { useCart } from '../context/CartContext';

const AnyComponent = () => {


const { cart, addToCart } = useCart();
return (
<>
<h3>Cart Items: {cart.length}</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.)?

You might also like