Generic Context Factories
What you'll learn: How to build a reusable factory function that generates typed context and hooks for any state shape, eliminating repetitive boilerplate.
The Problem with Repetition
By now, you've typed many contexts with their custom useContext hooks and provider components. Each time, you've written similar patterns: createContext<T | undefined>, checking for undefined, creating a provider wrapper. That's a lot of duplicate code.
What Is a Generic Context Factory?
A generic context factory is a function that takes a type parameter and returns everything you need for a fully-typed context: the provider component, the consumer hook, and proper type safety. It's like a template that works for any state shape you pass to it.
function createTypedContext<T>() {
const Context = createContext<T | undefined>(undefined);
function useTypedContext() {
const context = useContext(Context);
if (context === undefined) {
throw new Error('useContext must be used within Provider');
}
return context;
}
return [useTypedContext, Context.Provider] as const;
}
// Now use it for any state shape:
const [useUser, UserProvider] = createTypedContext<{ name: string; id: number }>();
const [useSettings, SettingsProvider] = createTypedContext<{ theme: 'light' | 'dark' }>();
Why This Matters
Instead of repeating the undefined check and custom hook pattern every time, you call createTypedContext<YourType>() once and get a complete, type-safe context setup. The generic <T> adapts to whatever type you provide.
Key Takeaway: Generic context factories eliminate boilerplate by creating a reusable template that generates typed contexts, providers, and consumer hooks for any state shape you need.