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:
- State Change: The user moves the mouse, triggering
handleMouseMove. - Set State:
setPositionupdates thepositionstate in theMouseTrackercomponent. - Re-render: React detects the state change and
re-renders
MouseTracker. - Execution: During the re-render, the
renderprop function is called with the fresh coordinates. - UI Update: The
Appcomponent receives the new coordinates via the function arguments and updates the DOM.
Best Practices for Updating Render Props
- Avoid Inline Function Re-creation: If you define
the render prop function inline inside a parent component’s render
method, it is created anew on every render. If this causes performance
issues or breaks downstream optimizations (like
React.memo), define the render function as an instance method or a memoized callback. - Keep State Localized: Only store the state that the render prop needs to update in the provider component. Unrelated state changes will cause unnecessary re-runs of the render prop function.