Skip to content

Instantly share code, notes, and snippets.

@pierodev0
Created March 16, 2025 17:38
Show Gist options
  • Save pierodev0/4ce1a1b1e8544bd588fa16480aba9d06 to your computer and use it in GitHub Desktop.
Save pierodev0/4ce1a1b1e8544bd588fa16480aba9d06 to your computer and use it in GitHub Desktop.
React TS Context Example
import { createContext, ReactNode, useContext, useState } from 'react';
import { Book } from 'types';
interface CartItem {
book: Book;
quantity: number;
}
interface CartContextType {
cart: CartItem[];
}
const CartContext = createContext<CartContextType | undefined>(undefined);
function CartProvider({ children }: { children: ReactNode }) {
const [cart, setCart] = useState<CartItem[]>([]);
return;
<CartContext.Provider value={{ cart }}>{children}</CartContext.Provider>;
}
export function useCart() {
const context = useContext(CartContext);
if (context === undefined) {
throw new Error('useCart must be used within a CartProvider');
}
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment