javascript / intermediate
Snippet
Compound Component Pattern with Context
The Compound Component pattern allows for a more expressive API by sharing state implicitly between a parent and its children. This is ideal for UI components like Tabs, Selects, or Accordions where children need to know about the parent's state.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const TabsContext = createContext({ activeTab: '', setActiveTab: (id: string) => {} });export function Tabs({ children, defaultTab }: { children: ReactNode, defaultTab: string }) {const [activeTab, setActiveTab] = useState(defaultTab);return (<TabsContext.Provider value={{ activeTab, setActiveTab }}><div className="tabs-container">{children}</div></TabsContext.Provider>);}Tabs.Tab = function Tab({ id, children }: { id: string, children: ReactNode }) {const { activeTab, setActiveTab } = useContext(TabsContext);return <button onClick={() => setActiveTab(id)} className={activeTab === id ? 'active' : ''}>{children}</button>;};
nextjs
Breakdown
1
const TabsContext = createContext(...);
Creates a shared state container for the component group.
2
Tabs.Tab = function Tab(...) { ... }
Attaches sub-components directly to the main component for a cleaner API.
3
const { activeTab, setActiveTab } = useContext(TabsContext);
Consumes the shared state within the child component.