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

Creating a Custom Provider Component

Building a wrapper component that encapsulates the Provider and manages its own state or logic.

Creating a Custom Provider Component

What you'll learn: How to bundle a Context Provider with its own state management logic into a reusable wrapper component.

The Core Idea

Instead of placing your Provider directly in App.tsx and managing its state there, you can create a custom Provider component that encapsulates both the Provider itself and all the logic needed to manage the context value. This keeps your Provider logic self-contained and your App component cleaner.

Think of it like building a specialized vending machine. Rather than having customers bring their own coins, track their own purchases, and manage inventory themselves, the vending machine handles all of that internally. Your custom Provider component is that self-sufficient machine.

Building a Custom Provider

Here's the pattern:

// ThemeContext.tsx
const ThemeContext = createContext<string | undefined>(undefined);

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState('light');

  // All Provider logic lives here
  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };

  const value = { theme, toggleTheme };

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

Now your App component is simpler:

function App() {
  return (
    <ThemeProvider>
      <YourComponents />
    </ThemeProvider>
  );
}

Why This Matters

You've moved the useState call and any related logic into the Provider component itself. This means:

  • The Provider owns and manages its state
  • State management logic is co-located with the Context
  • Your App component doesn't need to know implementation details
  • The Provider becomes portable and reusable

Key Takeaway: A custom Provider component wraps the Context.Provider and manages all state/logic internally, giving you a clean, reusable API that hides implementation details from parent components.