Course contentsShow
← React
Lesson 1094 of 2,39628. Composition: Compound ComponentsFree lesson

Type-Safe Context for Compound Components

TypeScript patterns for ensuring non-null context values and typed compound component APIs.

Type-Safe Context for Compound Components

What you'll learn: How to use TypeScript to prevent runtime errors and ensure your compound component context is always properly typed and non-null.


When you create a compound component with shared context, there's a hidden danger: the context value defaults to undefined or null. Without TypeScript guards, child components might crash when trying to access context properties that don't exist.

The Problem: Nullable Context

By default, createContext<MyContextType | null>(null) means every consumer must handle the null case. This creates verbose, repetitive code in every child component.

The Solution: Type-Safe Custom Hook

Instead of letting consumers handle null, your custom hook (from the previous lesson) should assert the context exists:

type TabsContextValue = {
  activeTab: string;
  setActiveTab: (id: string) => void;
};

const TabsContext = createContext<TabsContextValue | null>(null);

function useTabs() {
  const context = useContext(TabsContext);
  
  if (!context) {
    throw new Error('useTabs must be used within Tabs component');
  }
  
  return context; // TypeScript now knows this is never null
}

Now child components can destructure confidently:

function Tab({ id, children }: TabProps) {
  const { activeTab, setActiveTab } = useTabs(); // No null checks needed!
  // ...
}

Why This Works

The throw statement tells TypeScript that if execution continues past the null check, the context must be defined. The type narrows from TabsContextValue | null to just TabsContextValue.

This pattern gives you:

  • Compile-time safety: TypeScript knows the exact shape of your context
  • Runtime safety: Clear error messages if components are used incorrectly
  • Better DX: No repetitive null checks in child components

Key Takeaway: Use a custom hook with a null check to enforce proper context usage and eliminate nullable types from your compound component API, making it both safer and easier to use.