Created
March 16, 2025 17:38
-
-
Save pierodev0/4ce1a1b1e8544bd588fa16480aba9d06 to your computer and use it in GitHub Desktop.
React TS Context Example
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 { 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