Sub topic 16
Headless components and hooks
A headless component or hook supplies behavior, state, and accessibility attributes, and leaves all markup and styling to the caller. This chapter assumes you have read the earlier chapters in this tutorial on custom hooks, prop getters, the state reducer pattern, and controlled and uncontrolled components. It combines them into one design.
What "headless" means
A conventional component ships with a "head": its own elements, class names, and CSS. A headless one ships only the logic. You decide whether the result is a <button>, a <li>, or a custom SVG, and you decide how it looks.
You have already built the pieces:
- A custom hook holds the state and the transitions.
- Prop getters hand back the attributes and event handlers an element needs.
- A state reducer lets the consumer change how transitions behave.
- Control props let the consumer own the state.
Put together, those four patterns form a headless hook. Libraries such as Downshift, React Aria, Headless UI, and Radix primitives follow this approach, though some of them pair the logic with unstyled components instead of bare hooks.
A headless hook in practice
The useToggle hook from the previous chapter returns on, toggle, reset, and getTogglerProps. It never renders anything, so two unrelated UIs can share it.
import { useToggle } from './useToggle';
export function PlainButton() {
const { on, getTogglerProps } = useToggle();
return <button {...getTogglerProps()}>{on ? 'On' : 'Off'}</button>;
}
export function Chip() {
const { on, getTogglerProps } = useToggle({ initialOn: true });
return (
<span
role="button"
tabIndex={0}
style={{ background: on ? 'seagreen' : 'lightgray', padding: '0 8px' }}
{...getTogglerProps({
onKeyDown: (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
event.currentTarget.click();
}
},
})}
>
Filter
</span>
);
}PlainButton uses a native button, which handles the keyboard for free. Chip uses a span, so it has to add role, tabIndex, and key handling itself. The hook supplied the same state and aria-pressed to both. This is the main trade-off of headless design: you gain control of the markup and take on the responsibility for using it correctly.
A second example: a disclosure
Here is a hook that shows more of what a headless library handles. It links a button to the panel it controls through generated ids.
import { useId, useState } from 'react';
export function useDisclosure({ defaultOpen = false } = {}) {
const [open, setOpen] = useState(defaultOpen);
const id = useId();
const panelId = `${id}-panel`;
function getButtonProps({ onClick, ...rest } = {}) {
return {
'aria-expanded': open,
'aria-controls': panelId,
onClick: (event) => {
onClick?.(event);
if (!event.defaultPrevented) {
setOpen((prev) => !prev);
}
},
...rest,
};
}
function getPanelProps(props = {}) {
return { id: panelId, hidden: !open, ...props };
}
return { open, getButtonProps, getPanelProps };
}
export function FaqItem({ question, answer }) {
const { open, getButtonProps, getPanelProps } = useDisclosure();
return (
<section>
<h3>
<button {...getButtonProps()}>
{open ? '− ' : '+ '}
{question}
</button>
</h3>
<p {...getPanelProps()}>{answer}</p>
</section>
);
}Two details matter here. useId gives each instance its own id, so two FaqItem elements on one page never collide. And the button's handler checks event.defaultPrevented, so a consumer can cancel the toggle from its own onClick. That is the same override idea as a state reducer, applied at the event level.
Headless components
A hook is the simplest headless unit. When you want to offer a component API instead, wrap the hook in a render prop. The caller still supplies all of the markup.
import { useDisclosure } from './useDisclosure';
export function Disclosure({ children, ...options }) {
return children(useDisclosure(options));
}
export function Example() {
return (
<Disclosure defaultOpen>
{({ open, getButtonProps, getPanelProps }) => (
<div>
<button {...getButtonProps()}>{open ? 'Hide' : 'Show'}</button>
<div {...getPanelProps()}>Details</div>
</div>
)}
</Disclosure>
);
}The component form fits when the logic should live next to its markup in JSX. The hook form fits when you need to combine several pieces of behavior in one component. The compound-component form from earlier chapters fits when the parts must sit in separate places in the tree and coordinate through context. Many libraries expose the hook and build the component on top of it.
What a headless library must get right
Because the consumer chooses the elements, the library cannot assume anything about them. A solid headless API covers these points:
- Accessibility attributes. Roles,
aria-*state, and id wiring come from prop getters, so consumers cannot forget them. - Keyboard behavior. Arrow keys in a menu, Escape to close, and Enter or Space to activate belong in the logic, not in each consumer.
- Merged handlers. A getter must call the consumer's handler as well as its own, as
getTogglerPropsandgetButtonPropsdo. Overwriting the handler is the most common bug in hand-written getters. - Overridable behavior. A state reducer, control props, or both let consumers change outcomes without forking the code.
- Stable ids. Use
useIdrather than a module-level counter, which breaks server rendering because the server and the client generate different values.
Common errors
- Spreading getters in the wrong order. In
<button {...getButtonProps()} onClick={mine}>, youronClickreplaces the hook's handler, and the toggle stops working. Pass your handler into the getter instead:getButtonProps({ onClick: mine }). - Putting getters on the wrong element.
aria-controlson adivthat is not the toggle has no meaning to assistive technology. - Using non-interactive elements without the missing pieces. A
spanneeds a role, a tab stop, and key handling, asChipshows. A nativebuttonis almost always the better choice. - Returning a new object shape each render and depending on it. The getters are recreated on every render. This is fine for spreading into JSX. If you put a getter result in a dependency array, you will re-run the effect every time.
When headless is the right choice
| Situation | Better fit |
|---|---|
| One app, one design, one team | A styled component. Headless adds indirection you will not use. |
| A design system that must support several themes or brands | Headless logic with a styled layer on top. |
| Behavior is complex (menus, comboboxes, drag and drop) | A headless library. Rewriting its keyboard and focus logic is costly. |
| Simple, local state such as one boolean | A plain `useState`. A pattern here costs more than it saves. |
Headless code is also harder to debug. The behavior is split across a hook, its getters, and the consumer's markup, so a bug may sit in any of the three. Keep the getter surface small and document what each getter must be spread onto.
Exercise
The FaqItem author writes <button {...getButtonProps()} onClick={() => track('faq')}>. The panel no longer opens. What is wrong, and how do you fix it while keeping the tracking call?
Show answer
The explicit onClick that comes after the spread replaces the onClick returned by getButtonProps, so the hook's toggle handler never runs. Pass the handler through the getter so it is merged: <button {...getButtonProps({ onClick: () => track('faq') })}>. The getter calls the consumer's handler first and then toggles, unless the handler called event.preventDefault().
Exercise
Why does useDisclosure use useId instead of a counter variable defined at module level?
Show answer
A module-level counter can produce different values on the server and in the browser, which causes hydration mismatches. It also gives ids that depend on render order. useId produces ids that are stable and match between server and client, and unique per component instance.