Sub topic 14
Prop getters
This chapter assumes you can write custom hooks, use useState, pass event handlers as props, and use object spread and destructuring. It builds on the custom hooks chapter. It also leads into the state reducer chapter that follows.
The problem prop getters solve
A custom hook can return state and actions. The consumer then has to attach them to elements. For a toggle button, that means remembering to set aria-pressed, wire onClick, and keep both correct everywhere the hook is used.
The consumer also often needs its own onClick on the same element, for analytics or to close a menu. If the hook returned a ready-made props object, the consumer would have two bad options:
- Spread the object and then add
onClick. The consumer's handler replaces the hook's, and the toggle stops working. - Write the merge by hand each time, which is repetitive and easy to get wrong.
A prop getter is a function returned by the hook. It takes the consumer's props and returns the final props, with the hook's behavior merged in.
A first prop getter
import { useState } from 'react';
export function callAll(...fns) {
return (...args) => {
fns.forEach((fn) => {
if (typeof fn === 'function') fn(...args);
});
};
}
export function useToggle(initialOn = false) {
const [on, setOn] = useState(initialOn);
const toggle = () => setOn((prev) => !prev);
function getTogglerProps({ onClick, ...props } = {}) {
return {
'aria-pressed': on,
onClick: callAll(onClick, toggle),
...props,
};
}
return { on, toggle, getTogglerProps };
}The getter does three things:
- It pulls
onClickout of the arguments so it is not copied over the hook's handler. - It combines the consumer's handler and the hook's handler with
callAll. The consumer's runs first.callAllskips values that are not functions, so a missingonClickis safe. - It spreads the remaining props last, so the consumer can set
className,id, ordisabled.
Using it:
import { useToggle } from './useToggle';
export function Bookmark() {
const { on, getTogglerProps } = useToggle();
return (
<button
{...getTogglerProps({
className: 'bookmark',
onClick: () => console.log('bookmark clicked'),
})}
>
{on ? 'Saved' : 'Save'}
</button>
);
}A click logs the message and then flips on. The button gets aria-pressed without the consumer writing it.
Prop getter or prop collection
A prop collection is a plain object, such as togglerProps, that the consumer spreads. It is simpler, but it cannot merge handlers.
| Approach | Merges consumer handlers | Accepts extra props | Cost |
|---|---|---|---|
| Prop collection | No | No | Smallest API |
| Prop getter | Yes | Yes | Consumer must call a function |
Use a collection when the props are static and consumers rarely need to add their own handlers. Use a getter when the element is likely to be customized or when props depend on arguments.
Getters that coordinate several elements
Getters are most useful when one hook controls several elements that must agree with each other. An accessible disclosure needs a button and a panel linked by an id:
import { useId, useState } from 'react';
import { callAll } from './useToggle';
export function useDisclosure({ initialOpen = false } = {}) {
const [open, setOpen] = useState(initialOpen);
const id = useId();
const panelId = `${id}-panel`;
const toggle = () => setOpen((prev) => !prev);
function getButtonProps({ onClick, ...props } = {}) {
return {
'aria-expanded': open,
'aria-controls': panelId,
onClick: callAll(onClick, toggle),
...props,
};
}
function getPanelProps(props = {}) {
return { id: panelId, hidden: !open, ...props };
}
return { open, getButtonProps, getPanelProps };
}
export function Faq() {
const { getButtonProps, getPanelProps } = useDisclosure();
return (
<div>
<button {...getButtonProps()}>What is a prop getter?</button>
<p {...getPanelProps()}>A function that returns props for an element.</p>
</div>
);
}useId produces a stable, unique id, so two Faq components on one page never collide. The consumer cannot link aria-controls to the wrong element, because the hook creates both sides of the link.
Design rules and edge cases
- Decide who wins on conflicts. In
getTogglerProps,...propscomes last, so a consumer who passes'aria-pressed'replaces the hook's value. That gives control but allows the markup to drift out of sync with state. To make a prop non-overridable, put it after...props. - Merge every event handler the hook uses. If a getter attaches
onKeyDown, destructure and combine it the same way asonClick. Missing one handler is the most common prop getter bug. - Merge refs separately.
callAlldoes not work forref, because a ref can be an object as well as a function. If the hook needs a ref to an element, write a small ref-merging helper. - Always call the getter during render. It reads current state. Calling it once and caching the result produces stale
aria-*values. - Keep the getter's output stable in shape. It always returns the same keys, so spreading it never adds or removes attributes unexpectedly.
- Let consumers opt out. Some libraries let a consumer's handler cancel the hook's own behavior, for example by checking a flag on the event. This is powerful but harder to document. Add it only if consumers need it.
When prop getters fit
Prop getters work well in headless hooks, where the hook provides behavior and accessibility but the consumer provides all markup. They fit less well when you want to ship ready-made markup. In that case a compound component with context hides the wiring entirely. Choosing between these is covered in the final chapter on pattern trade-offs.
Exercise
A teammate writes this getter: function getTogglerProps({ onClick, ...props } = {}) { return { onClick: toggle, 'aria-pressed': on, ...props }; }. The consumer calls getTogglerProps({ onClick: track }). Does track run? Does the toggle still work? How would you fix the getter?
Show answer
Neither problem is hidden by the destructuring, so check the output. onClick is pulled out of props, so track is never included in the returned object and never runs. The toggle still works, because onClick: toggle stays in place. The consumer's handler is silently dropped. Fix it by returning onClick: callAll(onClick, toggle), so both handlers run.
Exercise
Why does useDisclosure build panelId inside the hook instead of asking the consumer to pass an id to both elements?
Show answer
The hook owns the link between aria-controls on the button and id on the panel. Generating the id with useId inside the hook guarantees both values match and are unique per instance. If the consumer supplied ids, they could mismatch or collide when the component appears more than once.