Course contentsShow
← React
Lesson 1051 of 2,39627. Composition: Render PropsFree lesson

Classic Example: Mouse Position Tracker

A MouseTracker component uses render props to share mouse coordinates with any rendering strategy the consumer chooses.

Classic Example: Mouse Position Tracker

You'll learn how to build a reusable MouseTracker component that shares mouse coordinates with any rendering strategy using render props.

The Core Idea

A mouse tracker is the classic render prop example because mouse position is stateful logic (tracking coordinates) that's completely separate from presentation (how you display those coordinates). One component owns the logic; consumers decide how to render it.

Think of it like a data service: the MouseTracker component "listens" to mouse movements and collects coordinates, but doesn't care whether you display them as text, use them to move an image, or draw a graph. The consumer passes a render function that receives { x, y } and returns JSX.

How It Works

The MouseTracker component:

  • Stores mouse position in state
  • Attaches a mousemove listener (often with useEffect)
  • Calls the render prop function with current x and y
  • Returns whatever JSX the consumer provides

Consumers pass different render functions to create completely different UIs from the same logic:

  • Display coordinates as text
  • Move a cat image to follow the cursor
  • Show a crosshair overlay
  • Draw a trail of dots

All without duplicating the mouse-tracking logic!

Why This Example Matters

This pattern demonstrates separation of concerns: the tracker knows what data to provide, consumers know how to present it. Before custom hooks existed, render props were the primary way to share stateful logic across components. Even today, render props excel when you need per-render control over rendering behavior.

Key Takeaway: A MouseTracker with render props separates mouse coordinate logic from presentation, letting consumers decide how to render the data without duplicating event handling code.