How to Update Render Props in React

This article explains how to update render props in React to ensure your components dynamically re-render when data changes. You will learn the underlying mechanism of render props, how state changes drive these updates, and see a practical code example demonstrating the pattern in action.

Understanding the Render Prop Update Mechanism

In React, a render prop is a technique for sharing code between components using a prop whose value is a function. Because a render prop is simply a function that returns a React element, it does not update on its own. Instead, it updates when the component containing the state (the provider component) undergoes a state or prop change.

To trigger an update in a render prop, you must update the internal state of the component that calls the render prop function. When that component’s state changes, it triggers a re-render, executing the render prop function again with the newly updated arguments.

Step-by-Step Implementation

Here is a straightforward example using a MouseTracker component. The wrapper component tracks the mouse position (state) and passes that coordinate data to the render prop function.

import React, { useState } from 'react';

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

  const handleMouseMove = (event) => {
    // Updating state triggers a re-render
    setPosition({
      x: event.clientX,
      y: event.clientY
    });
  };

  return (
    <div style={{ height: '100vh' }} onMouseMove={handleMouseMove}>
      {/* The render prop is called with the updated state */}
      {render(position)}
    </div>
  );
}

// Usage
function App() {
  return (
    <MouseTracker
      render={(coords) => (
        <h1>
          The mouse position is {coords.x}, {coords.y}
        </h1>
      )}
    />
  );
}

export default App;

How the Update Flows:

  1. State Change: The user moves the mouse, triggering handleMouseMove.
  2. Set State: setPosition updates the position state in the MouseTracker component.
  3. Re-render: React detects the state change and re-renders MouseTracker.
  4. Execution: During the re-render, the render prop function is called with the fresh coordinates.
  5. UI Update: The App component receives the new coordinates via the function arguments and updates the DOM.

Best Practices for Updating Render Props