0
0
ReactConceptBeginner · 3 min read

What is Render Props in React: Simple Explanation and Example

In React, render props is a pattern where a component takes a function as a prop and calls it to know what to render. This lets components share code and behavior by passing rendering logic as a function.
⚙️

How It Works

Render props work like giving a component a recipe to cook instead of the cooked meal. Instead of the component deciding exactly what to show, it asks you to provide a function that returns the UI it should render. This function is passed as a prop, often named render or simply as a child function.

Think of it like ordering coffee: you tell the barista exactly how you want it made (the function), and they prepare it for you. The component is the barista, and the render prop is your recipe. This way, the component can share its logic (like fetching data or handling events) but lets you decide how the UI looks.

💻

Example

This example shows a MouseTracker component that tracks mouse position and uses a render prop to tell React what to display with that position.

react
import React, { useState } from 'react';

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

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

  return (
    <div style={{ height: '100vh' }} onMouseMove={handleMouseMove}>
      {render(position)}
    </div>
  );
}

export default function App() {
  return (
    <MouseTracker render={({ x, y }) => (
      <h1>The mouse is at ({x}, {y})</h1>
    )} />
  );
}
Output
The mouse is at (x, y) where x and y update as you move the mouse inside the window.
🎯

When to Use

Use render props when you want to share behavior or state between components but keep the UI flexible. For example, if you have a component that tracks user input, animations, or data fetching, you can use render props to let other components decide how to show that data.

This pattern is great for reusable libraries or components where you want to separate logic from presentation. It helps avoid repeating code and keeps your app organized.

Key Points

  • Render props pass a function as a prop to control what a component renders.
  • This pattern helps share logic while keeping UI flexible.
  • It’s like giving a recipe instead of a finished dish.
  • Commonly used for reusable components that manage state or behavior.

Key Takeaways

Render props let components share logic by passing a function that returns UI.
They separate behavior from presentation, making components more reusable.
Use render props when you want flexible UI with shared state or behavior.
The render prop function receives data or state and returns React elements.
This pattern improves code organization and avoids duplication.