React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
What are render props?
Render Props is a technique for sharing code/logic between components using a prop whose value is a function that returns a React element. Instead of duplicating stateful logic in every component that needs it, a "provider" component encapsulates the logic and delegates what to render to its caller via this function prop.
jsx
<DataProvider render={(data) => <h1>{`Hello ${data.target}`}</h1>} />
Full example
jsx
class DataProvider extends React.Component {
state = { target: "World" };
render() {
// Instead of hardcoding what to render, delegate it via the render prop
return this.props.render(this.state);
}
}
function App() {
return (
<DataProvider render={(data) => <h1>{`Hello ${data.target}`}</h1>} />
);
}
perl
Here, `DataProvider` owns the state, but has no opinion on markup — any consumer can reuse the same logic while rendering completely different UI.
Why use render props?
markdown
1. **Cross-cutting logic reuse:** Encapsulates logic (data fetching, subscriptions, mouse/scroll tracking, form state, etc.) once and reuses it across many components without inheritance.
2. **Explicit data flow:** Unlike HOCs, which implicitly inject props, render props make it obvious exactly what data is being passed to the render function since it's right there as an argument.
3. **No naming collisions:** HOCs composed together can silently clash on injected prop names; with render props, you control the destructuring/naming at the call site.
4. **Flexible children API:** The render function doesn't need to be named `render` — the `children` prop can also be used as a function (see [Must a prop be named "render" for render props?](#is-it-prop-must-be-named-as-render-for-render-props)).
Common use cases
javascript
- Tracking mouse position / window size and sharing it with multiple components.
- Toggling UI state (modals, accordions, dropdowns) — see [How do you create HOC using render props?](#how-do-you-create-hoc-using-render-props).
- Fetching remote data and letting the consumer decide how to render loading/success/error states.
- Libraries such as React Router (`<Route render={...} />`) and Downshift use this pattern.
Downsides
vbnet
- Can lead to deeply nested JSX ("wrapper hell") when composing many render-prop components together.
- Defining an inline arrow function as the render prop on every render can hurt performance with `PureComponent`/`React.memo` since a new function reference is created each time (see [What are the problems with using render props with Pure Components?](#what-are-the-problems-of-using-render-props-with-pure-components)).
- Hooks now solve most of these use cases with less nesting and boilerplate — see [Do Hooks replace render props and higher-order components?](#do-hooks-replace-render-props-and-higher-order-components).