Course contentsShow
← React
Lesson 2378 of 2,39651. TypeScript with React BasicsFree lesson

Typing Provider Component Props

How to properly type the Provider wrapper component, including children and optional override props.

Typing Provider Component Props

What you'll learn: How to add TypeScript types to custom Provider wrapper components, including children and optional value overrides.

The Pattern

When you build a custom Provider component that wraps React Context, you need to type its props properly. This wrapper typically accepts children and sometimes allows consumers to override the default context value for testing or specialized cases.

Core Typing Structure

Your Provider component props should define:

  1. children – Always required; use ReactNode (the broadest type)
  2. Optional override props – Test values or partial overrides of the context state
interface ThemeProviderProps {
  children: ReactNode;
  initialTheme?: 'light' | 'dark'; // Optional override
}

function ThemeProvider({ children, initialTheme = 'light' }: ThemeProviderProps) {
  const [theme, setTheme] = useState(initialTheme);
  
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

When Overrides Matter

Override props shine in testing or when you need isolated instances:

interface AuthProviderProps {
  children: ReactNode;
  testUser?: User; // Inject authenticated user for tests
}

function AuthProvider({ children, testUser }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(testUser ?? null);
  // ... rest of auth logic
}

This lets test files pass testUser directly instead of mocking authentication flows.

The PropsWithChildren Shortcut

For simple cases with only children, use the utility:

function SimpleProvider({ children }: PropsWithChildren) {
  return <Context.Provider value={someValue}>{children}</Context.Provider>;
}

Key Takeaway: Type Provider props with ReactNode for children and specific optional types for any override values, enabling both production usage and testability.