Adding Flexibility with Render Props
What you'll learn: How to combine compound components with render props to give consumers ultimate control over rendering while maintaining shared state access.
The Core Idea
You've built compound components that share state through context—children implicitly get what they need. But sometimes consumers want more control: custom wrappers, conditional logic, or data transformation before rendering. By accepting render props within your compound component system, you let advanced users access the internal state directly while keeping the simple API for common cases.
Think of it like a restaurant kitchen: most customers order from the menu (standard compound components), but you can offer a "chef's table" experience where guests see the ingredients and customize the dish (render prop access to internal state).
How It Works
Your parent compound component already provides context. Now, add an optional render prop (or function-as-child) that receives the context value directly:
function Tabs({ children, render }) {
const [activeTab, setActiveTab] = useState('tab1');
const contextValue = { activeTab, setActiveTab };
return (
<TabsContext.Provider value={contextValue}>
{render ? render(contextValue) : children}
</TabsContext.Provider>
);
}
Consumers can now choose:
Standard usage:
<Tabs>
<Tabs.List>...</Tabs.List>
<Tabs.Panels>...</Tabs.Panels>
</Tabs>
Advanced usage with render prop:
<Tabs render={({ activeTab, setActiveTab }) => (
<div className={`custom-wrapper ${activeTab}`}>
<CustomHeader active={activeTab} />
<Tabs.List />
<Tabs.Panels />
</div>
)} />
The render prop pattern exposes your internal state machine, letting power users build custom layouts or logic while still leveraging your state management.
Key Takeaway: Adding render props to compound components provides an escape hatch for advanced customization without complicating the standard API—maintain simplicity for common cases while enabling flexibility when needed.