Rendering on Demand: Custom Logic with Render Props

Share stateful logic and let consumers decide how to render it. This brings flexibility for animations, mouse tracking, and permissions. Can get verbose, so prefer hooks for simpler cases.

A Render Prop is a technique where a component takes a function as a prop, and that function controls what gets rendered.

👉 Think of it like a chef handing you the recipe, and you decide how to cook it — the component provides data/logic, but you choose the UI.

Basics & Need

Sometimes you want to share logic (like fetching data, tracking mouse position, or handling form state) but give consumers full control over rendering.

Render Props separate what (logic) from how (UI).

How to Achieve It

// Logic Provider: MouseTracker
const MouseTracker = ({ render }) => {
const [pos, setPos] = React.useState({ x: 0, y: 0 });

return (
<div
onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}
style={{ height: "200px", border: "1px solid gray" }}
>
{render(pos)} {/* Render prop */}
</div>
);
};

// Usage
<MouseTracker
render={({ x, y }) => (
<h4>
Mouse is at {x}, {y}
</h4>
)}
/>;

👉 MouseTracker owns the logic.
👉 The parent decides the UI output.

Best Practices

  • Name the render prop clearly (e.g., render, children, or component).
  • Keep the function focused on rendering, not side effects.
  • Avoid deeply nested render props → they hurt readability.

Real-World Examples

  1. Authentication Gate<Auth>{({ user }) => user ? <Dashboard /> : <Login />}</Auth>
  2. Data Fetcher<Fetcher url="/api">{(data) => <Chart data={data} />}</Fetcher>
  3. Animation Wrapper<Animate>{(progress) => <Spinner speed={progress} />}</Animate>

Advantages

  • Flexible — consumer decides the UI.
  • Great for reusable logic providers (fetch, auth, track, animate).
  • Eliminates the need for inheritance.

Disadvantages

  • “Pyramid of Doom” → multiple nested render props become unreadable.
  • Can be verbose compared to Hooks.
  • Harder to debug with deeply nested inline functions.

Common Problems / Pitfalls

  • Forgetting to memoize heavy functions → re-renders on every change.
  • Overusing it when a simple prop/state would do.
  • Mixing render props with HOCs → messy code.

Summary Recommendation

Use Render Props when you want to share logic but give complete freedom over UI — e.g., data fetching, authentication, tracking, or animation. For newer React apps, custom hooks often replace render props, but this pattern is still a great way to understand and design reusable APIs.