Course contentsShow
← React
Lesson 279 of 2,3968. Props PatternsFree lesson

Render Props for Stateful Logic Reuse

Extracting stateful behavior (like mouse tracking or toggle state) into a component with a render prop.

Render Props for Stateful Logic Reuse

You'll learn how to extract stateful behavior into reusable components using render props.

Now that you understand the render prop pattern, let's see its true superpower: reusing stateful logic across different parts of your app without duplicating code.

The Problem: Duplicated Stateful Logic

Imagine you need mouse tracking in three different components. You could copy-paste the useState and useEffect logic three times, but that's messy. Instead, you can create a single component that manages the state and shares it through a render prop.

The Solution Pattern

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

  React.useEffect(() => {
    function handleMove(event) {
      setPosition({ x: event.clientX, y: event.clientY });
    }
    window.addEventListener('mousemove', handleMove);
    return () => window.removeEventListener('mousemove', handleMove);
  }, []);

  return render(position);
}

// Now reuse it anywhere:
<MouseTracker render={(pos) => <div>X: {pos.x}, Y: {pos.y}</div>} />
<MouseTracker render={(pos) => <Cursor x={pos.x} y={pos.y} />} />

The MouseTracker component owns the state and behavior. You tell it how to display that data through the render prop. Same stateful logic, different presentations.

Another Example: Toggle State

function Toggler({ render }) {
  const [isOn, setIsOn] = React.useState(false);
  const toggle = () => setIsOn(!isOn);

  return render(isOn, toggle);
}

<Toggler render={(isOn, toggle) => (
  <button onClick={toggle}>{isOn ? 'ON' : 'OFF'}</button>
)} />

Key Takeaway: Render props let you extract stateful behavior into a component that manages the logic while letting the consumer control the presentation—perfect for reusing things like mouse tracking, toggle state, or data fetching across multiple components.