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

Validating Context Usage

Add runtime checks to throw helpful errors when child components are used outside their parent.

Validating Context Usage

What you'll learn: How to catch developer mistakes early by ensuring compound component children are only used inside their intended parent.

The Problem: Context Without a Provider

When you build compound components that share state through Context, child components expect that Context to exist. But what happens if a developer accidentally uses <Tabs.Panel> outside of <Tabs>? They'll get cryptic runtime errors or undefined values that are hard to debug.

Think of it like a walkie-talkie system: if someone tries to receive a message without being on the right channel, they should get a clear "You're not connected!" warning, not static noise.

Adding Runtime Checks

The solution is to validate Context usage inside your custom hook. Instead of blindly trusting that useContext returns a value, check if it's undefined (which happens when there's no Provider):

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

Now every child component that calls useTabsContext() will get a helpful error message immediately if it's misplaced. The error appears right where the mistake happens, making it easy to fix.

Why This Matters

Without validation, bugs are silent and confusing. A missing Provider might cause subtle rendering issues or crashes deep in your component tree. With validation, you get a clear error at development time that says exactly what's wrong and how to fix it.

This pattern is standard in production libraries like Radix UI and Headless UI—it's part of building developer-friendly APIs.

Key Takeaway: Always validate Context usage in compound components by throwing descriptive errors when the Context is undefined, turning confusing bugs into actionable error messages.