Render Props Pattern

A render prop is a technique for sharing code between React components using a prop whose value is a function.

Core Concept

Instead of implementing its own render logic, a component with a render prop takes a function that returns a React element and calls it.

Basic Example

class Mouse extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

// Usage
<Mouse render={({ x, y }) => (
  <h1>The mouse position is ({x}, {y})</h1>
)}/>

Modern Hook Alternative

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

  useEffect(() => {
    const handleMouseMove = (e) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };

    window.addEventListener('mousemove', handleMouseMove);
    return () => window.removeEventListener('mousemove', handleMouseMove);
  }, []);

  return position;
}

// Usage
function MouseTracker() {
  const { x, y } = useMouse();
  return <h1>The mouse position is ({x}, {y})</h1>;
}

When to Use Render Props

  • Cross-cutting concerns (auth, data fetching)
  • Reusable stateful logic
  • When you need more flexibility than HOCs

Advantages

  • Explicit data flow
  • Dynamic composition
  • No namespace collisions

Disadvantages

  • Can lead to “callback hell”
  • Less elegant than hooks for simple cases
  • Performance considerations with inline functions