Sub topic 8
Building Compound Components with Context
This chapter assumes you know function components, props, JSX, useState, and passing functions as props. You should also be comfortable with ES modules and destructuring. Here you build a Tabs compound component whose parts share state through context. By the end you will know how the pieces fit, why context is needed, and which mistakes to avoid.
The problem context solves
A compound component is a group of components that work together and share implicit state. The HTML <select> and <option> pair is the classic example. <option> does not receive a selected prop from you, yet it knows what the <select> holds.
In React you could imitate this with React.Children.map and cloneElement, injecting props into direct children. That approach breaks as soon as a consumer wraps a child in a div or in another component, because only direct children get the injected props. Context removes this limit. Any descendant of the parent can read the shared state, however deeply it is nested.
The three parts
A context-based compound component has three parts.
- A context object, created with
createContext. - A parent component that owns the state and renders the context provider.
- Child components that read the context with
useContext.
Here is the complete implementation.
import { createContext, useContext, 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);
return (
<TabsContext.Provider value={{ value, setValue }}>
<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;How it works
Tabs holds one piece of state, the currently selected value. It puts value and setValue into the provider. Tab and Panel call useTabs(), which wraps useContext. When a tab is clicked, setValue runs, Tabs re-renders, and every consumer of the context re-renders with the new value. Each Panel compares its own value prop with the active one and renders only when they match.
The two value names mean different things. The value prop on Tab and Panel is an identifier that pairs a tab with its panel. The value in context is the identifier of the active tab. Destructuring with value: active keeps them apart.
The custom hook and the guard
createContext(null) sets the default to null. If someone renders <Tabs.Tab> outside <Tabs>, useContext returns that default. Without a check, the failure would be a vague error such as "Cannot destructure property 'value' of null", pointing inside your component.
The useTabs hook turns this into a clear message that names the cause. This is the guard against misuse. Putting it in one hook means every subcomponent gets it for free.
Using the component
The consumer decides the layout and order of the parts.
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 div with role="tablist" sits between Tabs and the Tab buttons. Under the cloneElement approach, that wrapper would stop the tabs from receiving props. With context it makes no difference. The consumer could also put the panels above the tabs, add a heading between them, or wrap each tab in a tooltip component. Compare this with a single <Tabs items={[...]} /> component. That version needs a new prop for every layout variation, such as icons, disabled tabs, or extra content.
Edge cases and common errors
A new context value on every render
value={{ value, setValue }} creates a new object each time Tabs renders. Every consumer re-renders whenever Tabs renders, even if value did not change. For a small tab set this cost is negligible. For a large tree, memoize the object.
import { createContext, useContext, useMemo, useState } from 'react';
const TabsContext = createContext(null);
export function Tabs({ defaultValue, children }) {
const [value, setValue] = useState(defaultValue);
const ctx = useMemo(() => ({ value, setValue }), [value]);
return (
<TabsContext.Provider value={ctx}>
<div>{children}</div>
</TabsContext.Provider>
);
}setValue from useState is stable, so it does not need to be in the dependency array. Memoizing only helps if Tabs itself re-renders for reasons other than value changing, for example when its own parent re-renders.
Missing or mismatched values
If a Panel has a value that no Tab uses, it never renders. If defaultValue matches no panel, the component shows tabs and no content. React does not warn about either case. Check that your identifiers match when a panel stays blank.
Using the context default as a feature
Some libraries give the context a working default instead of null. That allows subcomponents to render alone, which hides mistakes. A null default plus a guard is the safer choice for a compound component, because the parent is required for correct behavior.
Multiple instances
Each <Tabs> creates its own provider. Nested tabs work correctly, because a subcomponent reads the nearest provider above it. A Tabs.Tab inside an inner Tabs talks to the inner one only. This is usually what you want, but it means an inner tab cannot control an outer one.
Unstable component identity
Define Tab and Panel at module level, as shown. If you define them inside Tabs, React sees a new component type on every render, unmounts the old one, and loses its state.
Trade-offs
| Aspect | Context-based compound component | Single component with config props |
|---|---|---|
| Layout control | Consumer decides | Component decides |
| API size | Several named parts | One component, many props |
| Wrapper elements | Allowed at any depth | Not applicable |
| Misuse risk | Parts used outside parent, mismatched `value` | Invalid prop combinations |
| Re-renders | All consumers update on state change | Depends on implementation |
The pattern costs more code and gives the consumer more chances to make a mistake. It pays off when consumers need layout freedom.
Exercises
Exercise
A teammate renders <Tabs.Panel value="a"> on a page without a surrounding <Tabs>. What happens in the implementation above, and why is that better than having no guard?
Show answer
useTabs finds null from useContext and throws "Tabs subcomponents must be rendered inside <Tabs>". Without the guard, destructuring null would throw a generic TypeError that points inside the component and does not name the cause.
Exercise
Why does wrapping Tabs.Tab elements in a div role="tablist" work with the context version, but would fail with a React.Children.map and cloneElement version?
Show answer
cloneElement only injects props into the direct children that Tabs maps over, and the div becomes the direct child. The tabs inside it receive nothing. Context lets any descendant of the provider read the state, no matter how deeply it is nested.
Exercise
A Panel never appears even though its tab is clicked. Name two likely causes in this implementation.
Show answer
The value props on the Tab and Panel do not match, for example "two" versus "Two". Or the Panel is rendered outside the provider's subtree in a way that reads another Tabs instance, so it compares against a different active value.