Courses / React 19: From Components to Production / Chapter 25
Module 11 · Advanced Component Patterns · Chapter 25 of 30
Prop Getters: Merging Caller Props With Component Behaviour
Builds on Props Collections: Bundling the Props an Element Needs. Next up: State Initializer: Initial Values and Reset.
Part 1 · From collections to getters: one function that merges props
A collection that loses the caller's handler
The previous chapter returned collections, togglerProps and panelProps, that a caller spreads onto a button and its panel. It works until the caller wants its own click handler on the same button, for example to count how often a question is opened.
In JSX, when two sources give the same prop, the later one wins. Write {...togglerProps} onClick={track} and the caller's handler replaces the hook's, so the button never toggles. Write onClick={track} {...togglerProps} and the hook's handler replaces the caller's, so nothing is counted. The caller has to know the rule, remember it on every element, and pick which behaviour to lose.
A prop getter removes that choice. It is a function that the hook returns. The caller passes its own props in, and the getter returns the props to spread, with the hook's behaviour merged into them. Because the hook sees both sides before anything reaches the element, it can keep both handlers.
| Approach | Caller handler last | Caller handler first |
|---|