Script Valley
React.js: Complete Course
Component Patterns and Context APILesson 4.5

Render props pattern in React

render props definition, children as function, sharing stateful logic, render props vs hooks, mouse tracker example, data provider pattern, pitfalls

Render Props: Logic Without a Fixed UI

A render prop is a prop whose value is a function that returns JSX. The component with logic calls that function to delegate what to render. This separates behavior from presentation.

Mouse Tracker Example

import { useState } from 'react';

function MouseTracker({ children }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  function handleMouseMove(e) {
    setPosition({ x: e.clientX, y: e.clientY });
  }

  return (
    <div style={{ height: '200px' }} onMouseMove={handleMouseMove}>
      {children(position)}
    </div>
  );
}

// Usage โ€” consumer decides what to render
<MouseTracker>
  {({ x, y }) => <p>Mouse: {x}, {y}</p>}
</MouseTracker>

// Reuse with different rendering
<MouseTracker>
  {({ x, y }) => <Circle cx={x} cy={y} r={5} />}
</MouseTracker>

Render props solve the same reuse problem as HOCs but more explicitly โ€” the consumer sees exactly what data it receives. Custom hooks have largely replaced both patterns for logic sharing. Render props still shine for component-level inversion of control, where the parent component needs to delegate rendering decisions to the consumer.

Render props pattern in React โ€” Component Patterns and Context API โ€” React.js: Complete Course โ€” Script Valley โ€” Script Valley