Skip to content

Instantly share code, notes, and snippets.

@frandieguez
Last active April 9, 2026 18:52
Show Gist options
  • Select an option

  • Save frandieguez/8f4e6f572784483021101e8e45bfecf7 to your computer and use it in GitHub Desktop.

Select an option

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
import { CartProvider } from './src/hooks/useCart.js';
const App = ()=> (
<CartProvider>
<PizzaCard />
</CartProvider>
)
// 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;
// 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