Courses / React 19: From Components to Production / Chapter 24
Module 11 · Advanced Component Patterns · Chapter 24 of 30
Props Collections: Bundling the Props an Element Needs
Builds on Compound Components: Parts That Share State Through Context, Control Props: Components That Work Controlled or Uncontrolled, Advanced Hooks: Refs, Reducers, Context, Layout Effects and Custom Hooks, Architecting React Apps at Scale: Structure, State and Component APIs and Testing React: Components, Hooks, Network and End-to-End. Next up: Prop Getters: Merging Caller Props With Component Behaviour.
Part 1 · What a props collection is
Props that always travel together
A header button and its panel need a handful of props to work together: a click handler, aria-expanded, aria-controls and matching ids. This chapter bundles those props into objects that a hook returns, so each FAQ item on the exam-results page spreads them and cannot forget one.
Look at what one FAQ item needs. The button has to toggle the panel when clicked. It has to tell assistive technology whether the panel is open, with aria-expanded, and which element it controls, with aria-controls. The panel needs the id that aria-controls names, and a label that points back to the button. Between the button and the panel, every FAQ item repeats the same eight props, and every one is a chance for a typo.
A props collection is an object of props that a hook returns for the caller to spread onto an element. The hook owns the state and knows which props go together. The caller owns the markup and decides which element gets the collection. The architecture chapter called a hook like this headless: behaviour with no markup.
One hook, three collections
The useToggle hook below keeps one boolean and returns it with three collections. togglerProps belongs on the button that opens and closes the panel, panelProps on the panel itself, and closerProps on a Close button inside the panel: a button type and a click handler that only closes.
export function useToggle({ initialOn = false } = {}) { const [on, setOn] = useState(initialOn) const toggle = useCallback(() => setOn((cur) => !cur), []) const close = useCallback(() => setOn(false), []) const base = useId() const togglerId = `${base}-toggler` const panelId = `${base}-panel`
The first half of the hook: state, a toggle and the ids.
The ids come from useId, which the advanced hooks chapter covered, so two FAQ items on one page never collide. Each collection is built from the on flag and the ids, inside useMemo, so the object keeps its identity between renders unless a value in it changed.
const togglerProps = useMemo( () => ({ id: togglerId, 'aria-expanded': on, 'aria-controls': panelId, onClick: toggle, }), [on, togglerId, panelId, toggle], )
The toggler collection.
The names are a convention. togglerProps is for the element that toggles, and panelProps is for the panel it controls. Nothing stops a caller from spreading togglerProps on a div with role="button", but a native button already brings the keyboard behaviour that the ARIA attributes describe, so the collection leaves the element choice to the caller and expects a sensible one.
Notice that the handler is part of the collection. onClick: toggle is a prop like any other, and the button gets its behaviour from the spread and not from code the caller writes.
Spreading them
A caller writes the markup and spreads the collections onto the elements.
function FaqItem() { const { togglerProps, panelProps, closerProps } = useToggle() return ( <section> <h3> <button type="button" {...togglerProps}> What does revaluation cost? </button> </h3> <div {...panelProps}> <p>Rs 500 per paper.</p> <button {...closerProps}>Close</button> </div> </section> ) }
An FAQ item using the collections.
JSX spread, {...togglerProps}, copies each key of the object onto the element as a prop. A test rendered the item, printed its markup, clicked the header and clicked Close.
<section>
<h3>
<button
aria-controls="_r_0_-panel"
aria-expanded="false"
id="_r_0_-toggler"
type="button"
>
What does revaluation cost?
</button>
</h3>
<div
aria-labelledby="_r_0_-toggler"
hidden=""
id="_r_0_-panel"
role="region"
>
<p>
Rs 500 per paper.
</p>
<button
type="button"
>
Close
</button>
</div>
</section>
after the header click: true
after Close: falseReal run in jsdom with Testing Library's prettyDOM.
The button and the panel carry matching ids, the panel is hidden, and the header click set aria-expanded to true. The Close button received a type and a click handler. A handler is not an attribute, so the markup does not show it, but the click closed the item.
The pattern is small, and its value is in what the caller no longer writes. A caller cannot forget aria-controls, mismatch two ids or invent a different attribute name for the same job. When the rules for the widget change, the hook changes in one place.
Collections with control props
The previous chapter's useToggle took on, onChange and readOnly as well as initialOn. The version in this chapter keeps only initialOn so that the collections stay the subject, but nothing in them depends on that. A lab version kept its state in the previous chapter's useControllableState, returned the same three collections, and was driven by a parent that owned the value.
controlled, parent opened: true controlled, header clicked: false onChange saw [false]
Real run in jsdom: the same collections on top of useControllableState, controlled by a parent with an Open button.
The parent's button opened the item, and aria-expanded followed the parent's value. A header click asked for false through onChange, and the parent's state decided the result. The collections only read on and call toggle and close, so they work the same whichever side owns the state.
What is a props collection?
- An object of props returned by a hook, for the caller to spread onto an element, so the hook decides what the element needs and the caller decides which element it is.
Who owns the markup, and who owns the behaviour?
- The caller owns the markup, the elements and their styling. The hook owns the state and the props that connect the elements.
What does {...togglerProps} do in JSX?
- It copies each key of the object onto the element as a prop, so
aria-expanded,aria-controls,idandonClickall arrive at once.
Part 2 · Wiring ARIA for free
What the markup has to say
The two collections exist to get the ARIA wiring right once. The W3C's ARIA Authoring Practices Guide (APG) describes a disclosure, a button that shows or hides a section. Its page says the element that shows and hides the content has the role button, and has aria-expanded set to true when the content is visible and false when it is hidden. The button may also have aria-controls with the id of the element that holds the content. Enter and Space both toggle it, which a native button supplies.
The APG accordion page, which the compound components chapter used, adds that a panel may have role="region" and an aria-labelledby that names its button. The collections here include all of it: the toggler gets id, aria-expanded, aria-controls and onClick, and the panel gets id, role, aria-labelledby and hidden.
Ids that cannot clash
The easy way to link a button and a panel is a hard-coded id, faq-panel. It works until the page shows two FAQ items, when two elements share an id and the second button controls the first panel. The hook builds its ids from useId, which returns a different value in every component instance. It appends -toggler and -panel, so both ids in a pair share a base and no pair shares one with another.
The test below renders the hand-wired version with a fixed id twice, and the collections version twice, and runs axe-core on each. axe is the accessibility checker the testing chapter introduced. Version 4.14.0 ran inside jsdom, with the colour-contrast rule off because jsdom has no layout.
function Handwired({ q }: { q: string }) { const { on, toggle } = useToggle() return ( <section> <h3> <button type="button" aria-expanded={on} aria-controls="faq-panel" onClick={toggle} > {q} </button> </h3> <div id="faq-panel" hidden={!on}> Rs 500 per paper. </div> </section> ) }
The hand-wired version, with a fixed id in two places.
collections, closed: {"violations":[],"incomplete":[]}
collections, one open: {"violations":[],"incomplete":[]}
hand-wired ids, one open:
{"violations":[],"incomplete":["duplicate-id-aria"]}Real run in jsdom with axe-core 4.14.0. violations is what failed; incomplete is what axe could not decide. Long lines are wrapped to fit.
The collections version passed in both states. The hand-wired version had no violation, but axe listed duplicate-id-aria under incomplete rather than violations, which is the list it uses for results that need a person to confirm. Two elements with the same id, referenced by ARIA attributes, is what that rule looks for, and Deque's page for it rates the impact as critical. The reason it is not a violation here is in the rule's definition inside axe-core 4.14.0, which sets reviewOnFail: true: a failing check from this rule is filed as needs review. So a green list of violations is not the same as correct wiring, and the incomplete list is part of the result.
A mistake axe does catch
A hand-wired id can also just be wrong. The next test gave the button aria-controls="faq-pannel" while the panel's id was faq-panel, opened the item and ran axe.
typo in aria-controls, open: {"violations":["aria-valid-attr-value
(1)"],"incomplete":[]}Real run in jsdom, one item open, with the misspelled id. Long lines are wrapped to fit.
This time the tool reported a violation, one node, for an aria-controls value that points at nothing. The collections cannot produce this mistake, because both ids come from the same variable.
The item was open on purpose. In axe-core 4.14.0's source the id check for aria-controls is skipped when the same element has aria-expanded="false". A second test rendered the same typo closed and open.
typo, expanded=false {"violations":[],"incomplete":[]}
typo, expanded=true {"violations":["aria-valid-attr-value
(1)"],"incomplete":[]}Real run in jsdom with axe-core 4.14.0: the same misspelled aria-controls, closed then open. Long lines are wrapped to fit.
So a hand-wired typo on a collapsed item passes axe and is caught only after someone opens it. The rule page on Deque University describes the check as validating the values of ARIA attributes and does not mention this exception, so the behaviour above is from the source and the run, not from the documentation.
axe applies a set of rules to what is in the DOM. It cannot judge whether a panel's text makes sense, whether the heading level fits the page or how a screen reader announces the result. Treat a clean run as the minimum.
Why does the hook build its ids with useId?
- It returns a different value in every component instance, so two FAQ items never share an id. The hand-wired fixed id was shared and axe flagged it as incomplete.
What did axe report when aria-controls named an id that did not exist?
- A violation of
aria-valid-attr-value, one node, with the item open.
Part 3 · Collections for several elements
Three elements, one hook
An FAQ item has more than two elements that need props. The header button toggles it, the panel shows it, and a Close button inside a long answer should close it without scrolling back to the header. One hook call returns all three collections.
const closerProps = useMemo( () => ({ type: 'button' as const, onClick: close }), [close], )
The third collection, as the hook builds it.
The closer does not depend on on, so it never changes. as const keeps type as the literal 'button'. Without it TypeScript infers string, and a button rejects that. A short file spread an object without as const onto a button.
export function Probe() { const closerProps = { type: 'button', onClick: () => {} } const panelProps = { role: 'region', hidden: false } return ( <div {...panelProps}> <button {...closerProps}>Close</button> </div> ) }
The probe file: no as const.
widen.tsx(6,8): error TS2322: Type '{ type: string; onClick: () => void; children: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'. Type '{ type: string; onClick: () => void; children: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'. Types of property 'type' are incompatible. Type 'string' is not assignable to type '"button" | "reset" | "submit" | undefined'.
Real output of `tsc --noEmit`, folder shortened. Long lines are wrapped to fit.
The same file spread a panel object with a plain role: 'region' and compiled, because role accepts any string. The hook's as const on the role is harmless and not needed.
The same hook now gives an item what it needs for any of its elements, and each element only has to choose which collection to spread. A caller that wants no Close button simply never spreads closerProps.
Keeping them stable
The collections are objects, and a new object is created whenever a function runs unless something stops it. That matters when a collection is passed to a memoised component. memo compares props with Object.is, so a new object each render looks like a changed prop even when every value inside is the same.
The test below builds two versions of the hook, one with useMemo and one that returns plain objects. A memoised PanelBody receives the panel collection as a prop. An unrelated button re-renders the item without changing anything the collection depends on.
const PanelBody = memo(function PanelBody(props: { panel: Record<string, unknown> }) { renders.push('PanelBody') return <div {...props.panel}>Rs 500 per paper.</div> })
A memoised child that takes the collection as a prop.
useMemo: PanelBody renders after an unrelated render 0, after a toggle 1 plain objects: PanelBody renders after an unrelated render 1, after a toggle 1
Real run in jsdom: how many times PanelBody rendered. Long lines are wrapped to fit.
With useMemo, the unrelated render did not reach PanelBody, and a toggle rendered it once, which is correct because hidden changed. With plain objects, the unrelated render reached it too. A second test compared the object itself across two renders.
useMemo: same object after an unrelated render? true plain objects: same object after an unrelated render? false
Real run in jsdom: is the togglerProps object the same after a re-render that changed nothing in it?
Reference equality is the mechanism. The memoised hook returns the same object, and the plain version returns a new one each time.
What the memoisation depends on
useMemo is only as stable as its dependencies. The toggler collection lists on, the two ids and toggle, and toggle is stable because it is wrapped in useCallback with no dependencies and uses the updater form of the setter. If toggle were recreated on every render, the collection would be too, and the work above would be lost. The ids are stable because useId is stable for the life of the instance.
The same holds for dependency lists. A test put togglerProps in the dependency array of an effect and counted its runs.
useMemo: effect runs after mount 1, after three unrelated renders 1, after one toggle 2 plain objects: effect runs after mount 1, after three unrelated renders 4, after one toggle 5
Real run in jsdom: an effect that lists togglerProps. Three clicks on an unrelated button, then one toggle. Long lines are wrapped to fit.
The plain version ran the effect again after every render, and the memoised one only after the real change. Do not memoise because it feels tidy. The check is a render count, as the test did: if no memoised child receives the collection, a plain object is fine and simpler. The collection is worth stabilising when it reaches a memo component or a dependency list.
Why does the closer collection not change when the item opens?
- Its only dependency is the stable
closefunction. It does not readon.
In the run, why did PanelBody render once after a toggle even with useMemo?
hiddenis derived fromon, so the panel collection genuinely changed, and a memoised component must render when its props change.
What decides whether a collection keeps its identity between renders?
- Its
useMemodependencies. When none of them changed, the hook returns the same object, as the reference check showed.
Part 4 · Where collections break
A caller who needs a handler too
A collection is spread onto an element, and a caller often needs to add something of their own to the same element. The portal's analytics team wants a handler on the header button that records which question was opened. The element already has an onClick from the collection. In JSX, two props with the same name cannot both win, and the one that comes later replaces the other. A test tried both orders.
{props.order === 'caller-last' ? (
<button type="button" {...togglerProps} onClick={props.track}>
Revaluation?
</button>
) : (
<button type="button" onClick={props.track} {...togglerProps}>
Revaluation?
</button>
)}The two orders: the caller's onClick after the spread, and before it.
caller-last: aria-expanded=false, track calls=1 caller-first: aria-expanded=true, track calls=0
Real run in jsdom: a click on the header, then the two facts that matter.
With the caller's onClick after the spread, the tracking handler ran and the item did not open, because the caller's handler replaced the hook's. With it before the spread, the item opened and the tracking handler never ran, because the hook's handler replaced the caller's. In each order one behaviour is lost. In the first the button does nothing, and in the second the analytics stop.
The picture replays both halves of the story on one FAQ item: the collections working, then the caller's handler replacing the hook's, then the reverse order.
Watch for the props that travel with each collection
Read it as steps
What the compiler notices
TypeScript 7.0.2 flagged one of the two orders when the file was checked.
break.test.tsx(18,33): error TS2783: 'onClick' is specified more than once, so this usage will be overwritten.
Real output of `tsc --noEmit` on the same file, folder shortened. Long lines are wrapped to fit.
The error is for the case where a prop is written before a spread that also supplies it, so the first one is certain to be overwritten. The other order, with the caller's prop last, compiled without comment, although it also discards the hook's handler. The compiler can see a literal overwrite and cannot know that the thing being replaced was important.
The same hazard applies to any prop that both sides want. A caller's id can replace the generated one and break aria-controls. A caller's aria-expanded can lie about the state. A hidden prop on the panel can fight the one from the hook. Props that carry behaviour, such as event handlers, are the worst, because their absence leaves no mark in the markup.
What a fix has to do
A rough guide to who should win, by kind of prop, shows how many different rules a plain spread has to stand in for.
| Kind of prop | Example | What should happen |
|---|---|---|
| Event handler | onClick | both run, and the caller may cancel the hook's |
| ARIA wiring | aria-controls, id | the hook's value wins |
| Presentation | className | both contribute |
| State the hook owns | hidden on the panel | the hook's value wins |
Spread order is a blunt tool, because it chooses a winner and discards the loser. For event handlers neither side should lose: the hook's handler and the caller's handler both need to run, and the caller should be able to say that the hook's behaviour must not happen this time. For the ARIA attributes, the hook should win, because the wiring depends on them. For presentational props such as className, both sides should contribute.
A collection, being a plain object of fixed values, cannot express any of that. It cannot see the caller's props, because it was built before the caller wrote them. To merge, the hook would need to receive the caller's props and return a result that accounts for them. A function that takes props and returns merged props can do that, and a plain collection cannot.
In the run, what happened when the caller's onClick came after the spread?
- The caller's handler ran once and the item did not open. It replaced the hook's handler.
All chapters · Previous: Control Props: Components That Work Controlled or Uncontrolled