
"In React, it's always preferable to maintain a linear data flow. If a parent needs something, lift the state instead of smuggling it back up. All rules are made to be broken, though. Some (I think) valid use cases include: Building composible compound components, where the component tree is the source of data rather than passing it down via props. Managing <head /> tags. The parent can't realistically know what the title or description of the page is, but most metdata tags can't be rendered inline. Overriding page layout, e.g. removing page chrome on a leaf route, when said chrome is provided by the parent."
"What if List needs to know the number of items, or extract properties from children to build up state? We can easily map over the children and extract their props: Probably most of the time you want List to just own the data rather than do this, but sometimes this makes for a nicer, more composable component tree. However, it completely falls down if you want to support arbitrarily nested children: Which really reduces its usefulness as a composition primitive: the entire point of compound components is letting users control rendering."
"React ARIA/Spectrum has a very neat, if a bit wild, solution. They provide a 'collection' component API that looks like this: Their focus/state management (and more) requires knowledge of how many Item components there are, but each item might not be a direct child of a collection. Users may wish to wrap them for layout and/or styling. They perform a first-pass render to a fake 'document' inside a portal:"
"It works by implementing a tiny version of the DOM with just the methods React needs (e.g. createElement, appendChild, etc.). Then, it uses a React portal to render the collection into this fake DOM. React takes care of rendering all intermediary wrapper components, and leaf components like <Item&g"
React generally favors a linear data flow where state is lifted so parents own what children need. Exceptions can improve composability and correctness. Compound components can derive state from their children by extracting props, letting the component tree act as the data source. This approach can fail when children are arbitrarily nested because direct-child assumptions limit how rendering control works. Nested compound components can be supported by using a collection-style API that accounts for items not being direct children. A solution is to perform a first-pass render into a fake document created in a portal, implementing minimal DOM methods so React can render wrappers while still collecting item structure for focus and state management.
Read at Jayfreestone
Unable to calculate read time
Collection
[
|
...
]