Composition and Layout Components
Pass finished elements, not data, through components that only lay things out.
ReadModule 4 of 7
These notes are about designing component and hook APIs: how much control a component hands to whoever uses it, and how its pieces find each other without being wired up by hand. Each pattern answers that question differently:
The last four build one useToggle hook for the store's "Gift wrap" switch, handing over a little more control each time.
Every log, render list and DOM attribute here was recorded by running the product store in Chrome (examples/product-store/src/lessons/patterns).
These patterns come from component libraries you probably use: Radix and Reach (compound components), React Aria (slots), Downshift (prop getters, state reducer, control props). Recognizing them makes those libraries' APIs much easier to read.
Read them in order. Each one builds on the ones before it.
Pass finished elements, not data, through components that only lay things out.
ReadA function built once that still calls the newest callback: debounce done right, and useEffectEvent.
ReadToggle, ToggleButton, ToggleOn and ToggleOff sharing state through context, like select and option.
ReadA root component publishes props per slot name; generic Label, Input and Text pieces pick theirs up.
ReadHand out the props an element needs, and merge the consumer’s own handlers instead of overwriting them.
ReadLet the consumer choose the starting state, and make reset go back to it, even if the prop changes later.
ReadLet the consumer decide what each action does, by passing their own reducer that can veto or delegate.
ReadA hook that works on its own, or lets the parent own the value: suggestions through onChange, like input value.
Read