What is the render props pattern in React?
Short answer
The render props pattern means passing a function as a prop to a component, and that component calls the function to decide what to actually display, often passing some internal data or state into that function.
Advertisement
AModel answer
The render props pattern means passing a function as a prop to a component, and that component calls the function to decide what to actually display, often passing some internal data or state into that function. This lets you share logic between components while letting the parent fully control what gets rendered.
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
function handleMouseMove(e) {
setPosition({ x: e.clientX, y: e.clientY });
}
return <div onMouseMove={handleMouseMove}>{render(position)}</div>;
}
<MouseTracker render={(pos) => <p>Mouse is at {pos.x}, {pos.y}</p>} />Real-world example
A shared MouseTracker component tracks the mouse position once, and different pages use it to display that position in completely different ways, like showing coordinates in one place and moving an image in another, simply by passing a different render function.
Likely follow-ups
- How is the render props pattern different from simply passing children as a function?
- Why has this pattern become less common since custom hooks were introduced?
Related topics