Course contentsShow
← React
Lesson 806 of 2,39621. Context FundamentalsFree lesson

Extracting useContext into Custom Hooks

Learn the pattern of wrapping useContext in a custom hook for better ergonomics and error checking.

Extracting useContext into Custom Hooks

You'll learn how to wrap useContext in a custom hook to make your context consumption cleaner and safer.

The Ergonomics Problem

When you use useContext directly in components, you repeat the same import statements and context object references everywhere. More importantly, you can't enforce that the context is being used within a Provider—you'll only discover missing Providers at runtime when you get undefined values.

The Custom Hook Pattern

Instead of calling useContext(MyContext) in every component, create a custom hook that wraps it:

// ThemeContext.js
import { createContext, useContext } from 'react';

const ThemeContext = createContext(null);

export function ThemeProvider({ children }) {
  const value = { mode: 'dark', toggle: () => {} };
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === null) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

Now components just call useTheme() instead of importing both useContext and ThemeContext. The error checking happens automatically—if someone forgets the Provider, they get a clear error message immediately.

Why This Matters

This pattern turns your context into a proper API. Components don't need to know about useContext or the context object—they just call your custom hook. You control what gets returned, can add validation, and provide better error messages. It's one import instead of two, and you catch mistakes early.

Key Takeaway: Wrap useContext in a custom hook to hide implementation details, add error checking, and create a cleaner API for consuming context values.