Last active
April 9, 2026 18:52
-
-
Save frandieguez/8f4e6f572784483021101e8e45bfecf7 to your computer and use it in GitHub Desktop.
Example about how to use the React Context to share a provider and a hook to encapsulate state and modifiers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { CartProvider } from './src/hooks/useCart.js'; | |
| const App = ()=> ( | |
| <CartProvider> | |
| <PizzaCard /> | |
| </CartProvider> | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // src/components/PizzaCard.jsx | |
| import { useCart } from '../hooks/useCart'; | |
| function PizzaCard({ pizza }) { | |
| const { addItem } = useCart(); | |
| return <button onClick={() => addItem(pizza)}>Engadir</button>; | |
| } | |
| export default PizzaCard; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // src/hooks/useCart.js | |
| import { createContext, useContext, useState } from 'react'; | |
| const CartContext = createContext(null); | |
| export function CartProvider({ children }) { | |
| const [items, setItems] = useState([]); | |
| function addItem(pizza) { | |
| setItems(prev => [...prev, pizza]); | |
| } | |
| function removeItem(id) { | |
| setItems(prev => prev.filter(item => item.id !== id)); | |
| } | |
| function clearCart() { | |
| setItems([]); | |
| } | |
| return ( | |
| <CartContext.Provider value={{ items, addItem, removeItem, clearCart }}> | |
| {children} | |
| </CartContext.Provider> | |
| ); | |
| } | |
| export function useCart() { | |
| const context = useContext(CartContext); | |
| if (!context) throw new Error('useCart debe usarse dentro de CartProvider'); | |
| return context; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment