Custom Hooks for Consuming State and Dispatch
You'll learn how to create custom hooks that safely consume your context values and provide helpful error messages when used incorrectly.
Why Custom Hooks Matter
After creating your Context pair (one for state, one for dispatch), you could let components consume them directly with useContext. But there's a better pattern: wrap those useContext calls in custom hooks with descriptive names and safety checks.
The Pattern
Create two hooks—typically named useAppState and useAppDispatch:
function useAppState() {
const context = useContext(AppStateContext);
if (context === undefined) {
throw new Error('useAppState must be used within AppProvider');
}
return context;
}
function useAppDispatch() {
const context = useContext(AppDispatchContext);
if (context === undefined) {
throw new Error('useAppDispatch must be used within AppProvider');
}
return context;
}
The Benefits
Encapsulation: Components don't need to know they're using Context—they just call useAppState().
Clear Error Messages: If someone tries using the hook outside the Provider, they get a helpful error immediately, not undefined mysteriously breaking later.
Refactoring Safety: You can change the internal implementation (maybe switch from Context to another solution) without touching every component.
Better Names: useAppState() is more descriptive than useContext(AppStateContext).
Usage in Components
function MyComponent() {
const state = useAppState();
const dispatch = useAppDispatch();
// Now safely use state and dispatch
}
Key Takeaway: Custom hooks that wrap useContext calls provide type safety, clear error messages when used outside the Provider, and create a cleaner API for consuming your global state and dispatch function.