javascript / expert
Snippet
Compound Components Pattern with Context API
The Compound Components pattern allows you to create a set of components that work together to share state implicitly. This enhances API flexibility and avoids 'prop drilling' by using React Context to manage the internal state of a complex UI component like a Tab system.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const TabsContext = React.createContext();function Tabs({ children, defaultValue }) {const [activeTab, setActiveTab] = React.useState(defaultValue);const value = React.useMemo(() => ({ activeTab, setActiveTab }), [activeTab]);return <TabsContext.Provider value={value}>{children}</TabsContext.Provider>;}Tabs.Trigger = function Trigger({ value, children }) {const { activeTab, setActiveTab } = React.useContext(TabsContext);return <button onClick={() => setActiveTab(value)} className={activeTab === value ? 'active' : ''}>{children}</button>;};Tabs.Content = function Content({ value, children }) {const { activeTab } = React.useContext(TabsContext);return activeTab === value ? <div>{children}</div> : null;};
react
Breakdown
1
const TabsContext = React.createContext();
Creates a context to hold the shared state between parent and child components.
2
Tabs.Trigger = function Trigger({ value, children }) { ... }
Attaches sub-components directly to the main component object for a clean, namespaced API.