typescriptadvanced
Context Provider Factory
Utility function that creates a typed React Context with a Provider and a custom hook in one call.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { createContext, useContext, ReactNode } from 'react';
export function createSafeContext<T>(displayName: string) {
const Context = createContext<T | null>(null);
Context.displayName = displayName;
function useCtx(): T {
const value = useContext(Context);
if (value === null) {
throw new Error(`use${displayName} must be used within a ${displayName}Provider`);
}
return value;
}
function Provider({ value, children }: { value: T; children: ReactNode }) {
return <Context.Provider value={value}>{children}</Context.Provider>;
}
return [Provider, useCtx] as const;
}
// Usage:
// const [ThemeProvider, useTheme] = createSafeContext<{ dark: boolean }>('Theme');
// <ThemeProvider value={{ dark: true }}><App /></ThemeProvider>Use Cases
- Creating typed contexts
- Reducing context boilerplate
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Compound Component Pattern
Build flexible compound components using React Context for implicit parent-child communication.
Best for: Accordion components
#patterns#compound-component
typescriptadvanced
React Compound Component Pattern
Build flexible compound components using React context for shared state between related parts.
Best for: Building flexible component libraries
#react#patterns
typescriptadvanced
Context Selector Pattern
Avoid unnecessary re-renders with a context selector pattern that subscribes to specific state slices.
Best for: High-performance global state
#react#context
typescriptadvanced
Context + useReducer State Management
Type-safe global state pattern combining React Context with useReducer for complex state without external libs.
Best for: Global application state
#context#reducer