Sub topic 12
Control props for compound components
This chapter assumes you can read the Tabs compound component built earlier with context, and that you know the difference between controlled and uncontrolled inputs. You should also be comfortable with useState and passing callbacks as props.
The problem control props solve
The Tabs component from the earlier chapter owns its selected value. That works until a consumer needs to take part in the decision. Some examples:
- Keep the selected tab in the URL.
- Block a tab change while a form has unsaved edits.
- Open a specific tab from a button elsewhere on the page.
Each case needs the parent to read the value and to approve or reject changes. A component that only keeps private state cannot do that.
A control prop is a prop that lets the consumer take over one piece of the component's state. For Tabs, the control prop is value. It comes with a change callback, onValueChange. This is the same contract as <input value onChange>, applied to a compound component.
Two modes, one component
The component runs in one of two modes, and the mode is decided by whether the consumer passed value.
| Mode | Consumer passes | Who stores the state | How changes are reported |
|---|---|---|---|
| Uncontrolled | `defaultValue` (optional) | The component | `onValueChange` is optional and informational |
| Controlled | `value` and `onValueChange` | The consumer | `onValueChange` is the only way to request a change |
In controlled mode the component never changes what it shows on its own. It reports the requested value, and the consumer decides whether to pass that value back down.
Extracting a reusable hook
You could write the controlled/uncontrolled branching inside Tabs. Every compound component with a control prop needs the same logic, so put it in a hook.
import { useCallback, useRef, useState } from 'react';
export function useControllableState({ value, defaultValue, onChange }) {
const isControlled = value !== undefined;
const wasControlled = useRef(isControlled);
const [internal, setInternal] = useState(defaultValue);
if (wasControlled.current !== isControlled) {
console.warn(
'A component changed from ' +
(wasControlled.current ? 'controlled to uncontrolled' : 'uncontrolled to controlled') +
'. Decide on one mode for the lifetime of the component.'
);
wasControlled.current = isControlled;
}
const current = isControlled ? value : internal;
const setValue = useCallback(
(next) => {
if (!isControlled) {
setInternal(next);
}
onChange?.(next);
},
[isControlled, onChange]
);
return [current, setValue];
}Three details matter here:
- The test is
value !== undefined, notvalue != null. Passingnullis a legitimate controlled value, for example "no tab selected". onChangeis called in both modes. In uncontrolled mode it is a notification, and in controlled mode it is the request.- The ref remembers the mode at the first render so the hook can warn when a consumer switches modes.
Applying it to Tabs
Tabs now delegates its state to the hook and shares the result through context. Tab and Panel do not change, because they only read the context.
import { createContext, useContext, useMemo } from 'react';
import { useControllableState } from './useControllableState';
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({ value, defaultValue, onValueChange, children }) {
const [current, setCurrent] = useControllableState({
value,
defaultValue,
onChange: onValueChange,
});
const ctx = useMemo(() => ({ value: current, setValue: setCurrent }), [current, setCurrent]);
return (
<TabsContext.Provider value={ctx}>
<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;Because the subcomponents call setValue from context, they work in both modes without knowing which one is active. This is why control props fit compound components well. The mode is decided in one place, the parent.
Using it in both modes
The uncontrolled usage is unchanged:
<Tabs defaultValue="one">...</Tabs>For controlled usage, this parent blocks tab changes while a form has unsaved edits:
import { useState } from 'react';
import { Tabs } from './Tabs';
export function Settings() {
const [tab, setTab] = useState('profile');
const [dirty, setDirty] = useState(false);
function handleChange(next) {
if (dirty && !window.confirm('Discard unsaved changes?')) {
return;
}
setDirty(false);
setTab(next);
}
return (
<Tabs value={tab} onValueChange={handleChange}>
<div role="tablist">
<Tabs.Tab value="profile">Profile</Tabs.Tab>
<Tabs.Tab value="billing">Billing</Tabs.Tab>
</div>
<Tabs.Panel value="profile">
<input onChange={() => setDirty(true)} aria-label="Display name" />
</Tabs.Panel>
<Tabs.Panel value="billing">Billing details</Tabs.Panel>
</Tabs>
);
}When the user cancels the confirmation, handleChange returns without calling setTab. The value prop stays the same, so the selected tab does not change.
Common errors
- Passing
valuewithoutonValueChange. The tabs become read-only. Clicks fire nothing useful and the display never changes. React warns for<input>, but your component will not unless you add a check. - Passing
value={undefined}by accident. A variable that is brieflyundefined, such as data that has not loaded, puts the component in uncontrolled mode. When the data arrives, the mode flips. Usenullfor "nothing selected", or give the state an initial value. - Passing both
valueanddefaultValue.defaultValueis ignored in controlled mode. Document this, or warn. - Calling
onChangeinside a state updater function. Updater functions can run more than once in development under Strict Mode, which would fire the callback twice. CallonChangefrom the event path, as the hook does. - Memoizing without a stable callback. If the consumer passes a new
onValueChangefunction each render,setValuechanges identity each render. That is harmless here, but it will re-run effects that depend on it.
Choosing which state to expose
Control props apply to any piece of state a consumer might need to own. A Dialog exposes open and onOpenChange. An Accordion might expose value as an array of open item ids. Add a control prop for state that consumers have real reasons to manage, and keep everything else internal. Each control prop adds a mode to test and document.
For consumers who need to change how state transitions work, not just own the value, a control prop is not enough. The state reducer pattern, covered later, handles that case.
Exercise
A consumer renders <Tabs value={selected} onValueChange={setSelected}>, where selected comes from a fetch and is undefined until the response arrives. The tabs work after loading but React logs a warning about switching from uncontrolled to controlled. Why does this happen, and how do you fix it?
Show answer
While selected is undefined, the hook sees value === undefined and runs in uncontrolled mode. When the fetch finishes, value becomes defined and the hook switches to controlled mode, which triggers the warning. Fix it by giving the state a defined initial value, for example useState(null) or a default tab id, so the component is controlled from the first render. If "no selection" is valid, use null, because the hook treats null as a controlled value.