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

Enforcing Context Usage: Custom Hook Pattern

Creating a useCompoundContext hook that throws if used outside the parent component tree.

Enforcing Context Usage: Custom Hook Pattern

You'll learn how to prevent compound components from being used incorrectly by creating a custom hook that validates the context.

The Problem with Naked Context

When you share state through context in compound components, there's nothing stopping someone from using a child component outside the parent tree. They'll consume the context, get undefined, and either crash or behave unpredictably. It's like trying to use a remote control without a TV nearby—technically possible, but pointless and confusing.

The Custom Hook Guard

Instead of calling useContext directly in child components, create a wrapper hook that validates the context exists:

const TabsContext = createContext(null);

function useTabsContext() {
  const context = useContext(TabsContext);
  
  if (context === null) {
    throw new Error(
      'Tabs compound components must be used within <Tabs>'
    );
  }
  
  return context;
}

Now in your child components, use useTabsContext() instead of useContext(TabsContext):

function TabList({ children }) {
  const { activeTab } = useTabsContext(); // Safe!
  // ...
}

Why This Matters

If someone accidentally writes <TabList> without wrapping it in <Tabs>, they get an immediate, clear error message instead of a cryptic "Cannot read property of undefined" later. It's fail-fast design—catch mistakes at the boundaries.

This pattern also documents where the component belongs, making your API self-explanatory.

Key Takeaway: A custom context hook with a null-check ensures compound components fail fast with helpful errors when used outside their parent, making your API safer and more discoverable.