Sub topic 8
Building compound components with context
This chapter assumes you know function components, useState, and passing props and event handlers. It also assumes you have seen createContext and useContext in the previous chapter. Here you will combine them to build a Tabs compound component.
The problem context solves
A compound component is a set of components that work together and share hidden state. The parent owns the state. The children read and update it.
You could pass value and setValue to every child as props. The consumer would then have to wire them by hand, and the consumer could not freely wrap or reorder the children. Context removes that wiring. The parent publishes its state, and any descendant can read it, however deeply it is nested.
The structure
The implementation
import { createContext, useContext, useMemo, useState } from 'react';
const TabsContext = createContext(null);
function useTabs() {
const ctx = useContext(TabsContext);
if (!ctx) {
throw new Error('Tabs subcomponents must be rendered inside <Tabs>');
}
return ctx;
}
export function Tabs({ defaultValue, children }) {
const [value, setValue] = useState(defaultValue);
const context = useMemo(() => ({ value, setValue }), [value]);
return (
<TabsContext.Provider value={context}>
<div>{children}</div>
</TabsContext.Provider>
);
}
function Tab({ value, children }) {
const { value: active, setValue } = useTabs();
return (
<button role="tab" aria-selected={active === value} onClick={() => setValue(value)}>
{children}
</button>
);
}
function Panel({ value, children }) {
const { value: active } = useTabs();
return active === value ? <div role="tabpanel">{children}</div> : null;
}
Tabs.Tab = Tab;
Tabs.Panel = Panel;Four details matter here:
createContext(null)usesnullas the default. A component rendered outside<Tabs>therefore getsnull, which the guard can detect.useTabsis a small custom hook. It keeps the guard in one place and gives a clear error message instead of a confusing "cannot destructure null".TabandPaneltake avalueprop that identifies them. They compare it with the sharedvalueto decide whether they are active.useMemokeeps the context object the same between renders unlessvaluechanges. Without it,{ value, setValue }is a new object on every render ofTabs. Every consumer would then re-render each time the parent re-renders.
Using it
import { Tabs } from './Tabs';
export function Example() {
return (
<Tabs defaultValue="one">
<div role="tablist">
<Tabs.Tab value="one">One</Tabs.Tab>
<Tabs.Tab value="two">Two</Tabs.Tab>
</div>
<Tabs.Panel value="one">First panel</Tabs.Panel>
<Tabs.Panel value="two">Second panel</Tabs.Panel>
</Tabs>
);
}The consumer chooses the layout and the order. It can put the panels above the tabs or wrap each tab in extra markup. Nothing is passed between the parts by hand.
Common errors
- Forgetting the guard. A
Tabused outsideTabsthen fails with an unclear message. - Putting
{ value, setValue }inline in the provider without memoizing it, which causes extra re-renders. - Using the same
valuestring on two tabs. Both would then show as selected.
Exercise
Why does the useTabs hook throw an error when the context is null, and what must be true of the createContext default for that check to work?
Show answer
A Tab or Panel rendered outside <Tabs> has no provider above it, so useContext returns the default value. The check only works if the default is null (or another falsy sentinel). Then the hook can detect the missing provider and throw a clear message. If the default were a real object, misuse would go unnoticed.