typescriptadvanced

Context Provider Factory

Utility function that creates a typed React Context with a Provider and a custom hook in one call.

typescript
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.