Sharing Stateful Logic with Render Props
What you'll learn: How render props let you extract stateful logic while giving consumers full control over what gets rendered.
The Core Pattern
Render props shine when you need to share stateful behavior (like mouse tracking, toggling, or data fetching) but let different consumers present that data differently.
Instead of hard-coding what a component renders, you give it a function prop that returns JSX. The component manages the state and calls your function with that state as arguments.
A Practical Example
Imagine a MouseTracker component that tracks cursor position:
function MouseTracker({ render }) {
const [position, setPosition] = React.useState({ x: 0, y: 0 });
React.useEffect(() => {
function handleMove(e) {
setPosition({ x: e.clientX, y: e.clientY });
}
window.addEventListener('mousemove', handleMove);
return () => window.removeEventListener('mousemove', handleMove);
}, []);
return render(position);
}
Now different consumers can use the same logic but render differently:
// Consumer A: Simple coordinates
<MouseTracker render={(pos) => <p>Mouse: {pos.x}, {pos.y}</p>} />
// Consumer B: Visual dot
<MouseTracker render={(pos) => (
<div style={{ position: 'absolute', left: pos.x, top: pos.y }}>
🎯
</div>
)} />
The Power Move
The MouseTracker owns the how (tracking logic, state management). The consumer owns the what (presentation). This separation makes the logic reusable across radically different UIs without duplication.
Key Takeaway: Render props extract stateful logic into a reusable component while keeping presentation flexible—the component manages state and behavior, calling your function with that state so you control rendering.