React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
What are render props?
junior LevelCode ExampleComponentsHooks
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
arduino
- Tracking mouse position / window si