Render props
Hand rendering control to the caller through a function child, and when a hook is the better answer.
- #react
- #patterns
- #composition
A component takes a function and calls it with its internal state, so the caller decides what to render.
The pattern
When a hook is better
For state logic with no markup of its own, a hook is shorter and avoids the nesting that render props pile up:
Render props are still the right answer when the component renders something itself, such as a measurement wrapper, a virtualized container or a portal boundary, and delegates only part of the output.
Avoiding needless re-renders
An inline function child is a new reference on every render, so memo on the wrapper never matches. If the wrapper is expensive, hoist the function out or move to a hook.
Related entries
- Compound components. Better when the caller needs structure rather than values.
- Virtual list. A render prop that earns its place, because the container measures and the caller renders the rows.
Related entries
Compound components
Expose a component's internals as named subcomponents that share state through a private context.
Error boundaries
Keep a render-time failure inside one subtree, and recover from it without a full page reload.
useEventListener hook
Attach a DOM event listener once and keep the handler current, so a changing callback never detaches the listener.