Skip to main content

Command Palette

Search for a command to run...

41) Render Props

Updated
View as Markdown
  1. In React, Render Props is a pattern for sharing logic between components by passing a function as a prop. That function returns JSX, giving the parent control over what to render while the child handles how the logic works.
    Before hooks, sharing logic often meant:
    Duplicating code ❌
    Using inheritance ❌
    Render Props introduced a cleaner approach:
    Reuse logic ✅
    Keep UI flexible ✅

  2. Basic Example

    const MouseTracker = ({ render }) => {
      const [position, setPosition] = React.useState({ x: 0, y: 0 });
    
      return (
        <div onMouseMove={(e) => setPosition({ x: e.clientX, y: e.clientY })}>
          {render(position)}
        </div>
      );
    }
    
    <MouseTracker
      render={(pos) => (
        <h1>Mouse Position: {pos.x}, {pos.y}</h1>
      )}
    />
    

    i) The logic (mouse tracking) is reused
    ii) The UI is controlled by the caller

  3. Render Props is a React pattern where a component receives a function as a prop to dynamically decide what to render, enabling reusable logic with flexible UI.