// Encapsulate context + hook in a moduleconstCtx=createContext(null);exportfunctionuseMyContext(){const ctx =useContext(Ctx);if(!ctx)thrownewError('Missing Provider');return ctx;}
Example
import{ createContext,useContext,useState}from'react';constCartContext=createContext(null);exportfunctionCartProvider({ children }){const[items, setItems]=useState([]);functionaddItem(product){setItems(prev =>[...prev,{...product, qty:1}]);}functionremoveItem(id){setItems(prev => prev.filter(item => item.id!== id));}const totalItems = items.reduce((sum, i)=> sum + i.qty,0);return(<CartContext.Provider value={{ items, addItem, removeItem, totalItems }}>{children}</CartContext.Provider>);}exportfunctionuseCart(){const context =useContext(CartContext);if(!context){thrownewError('useCart must be used within a CartProvider');}return context;}
Note Exporting a custom hook that throws when the Provider is missing catches mistakes early and gives a clear error message instead of undefined values that silently break downstream.
Note This pattern provides Redux-like state management with built-in React APIs. Splitting state and dispatch into separate contexts prevents components that only dispatch actions from re-rendering when state changes.
Frequently asked questions
How does React handle provider pattern?
React covers this with 2 copy-ready snippets on this page. The "Context with State (Custom Hook)" snippet in React uses `// Encapsulate context + hook in a module`.
Which code does the React example use?
The "Context with State (Custom Hook)" snippet uses `// Encapsulate context + hook in a module`, from the useContext section of the React cheat sheet.
What other React snippets are shown for "provider pattern"?
Besides "Context with State (Custom Hook)", this page also shows "Context + Reducer Pattern".
Is there anything to watch out for?
Yes. For "Context with State (Custom Hook)": Exporting a custom hook that throws when the Provider is missing catches mistakes early and gives a clear error message instead of undefined values that silently break downstream.