What is the Render Props pattern and when would you still use it?
Hint
Pass a function as a prop that returns JSX — the component calls it with its internal state
Full Answer
// Render props — component shares state by calling a function prop
function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div onMouseMove={e => setPos({ x: e.clientX, y: e.clientY })}>
{render(pos)} {/* caller decides what to render */}
</div>
);
}
// Usage
<MouseTracker render={({ x, y }) => (
<p>Mouse at {x}, {y}</p>
)} />
// children as a function (same pattern)
<MouseTracker>
{({ x, y }) => <Circle x={x} y={y} />}
</MouseTracker>
Render props vs custom hooks:
- Custom hooks replaced most render prop use cases (simpler, less nesting)
- Render props still shine when you need to inject JSX into a specific DOM location managed by the component
- Libraries like React Table, Downshift, and Formik use render props for maximum flexibility
💡 If the render prop is just sharing state logic, refactor to a custom hook. If it's about rendering into a specific slot (like a virtualized list rendering each row), render props are still the right tool.
More Component Patterns Questions
Practice this in a timed sprint
5 free questions, no signup required