Provider Pattern with Custom Hooks in React
From the React Design Patterns cheat sheet · Component API Patterns · verified Jul 2026
Provider Pattern with Custom Hooks
Wrap context with a Provider component and a custom hook for safe consumption
jsx
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return <ThemeContext value={{ theme, setTheme }}>{children}</ThemeContext>;
}
function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be inside ThemeProvider');
return ctx;
}💡 The Provider + custom hook combo is the standard way to expose Context safely
⚡ Throwing in the custom hook gives clear errors when the Provider is missing
📌 Encapsulating state inside the Provider lets you refactor to Zustand/Jotai later without breaking consumers
🟢 Split state and dispatch into separate contexts to prevent unnecessary re-renders
providercontextcustom-hooks