Render Props
📖 Concept
Render Props refers to a technique for sharing code between React components using a prop whose value is a function.
The Concept: Instead of a component rendering its own UI, it takes a function as a prop and calls that function to know what to render. This allows the parent to decide how the data should be displayed while the child handles the logic.
Use Case: Sharing stateful logic (like mouse position, scroll position, or data fetching) between components that have different UIs.
Note: While many render prop use cases have been replaced by Custom Hooks (Phase 13), it's still an important pattern used in libraries like Formik and React Router.
💻 Code Example
1import React, { useState } from 'react';23// 1. Logic Component4const MouseTracker = ({ render }) => {5 const [position, setPosition] = useState({ x: 0, y: 0 });67 const handleMouseMove = (event) => {8 setPosition({9 x: event.clientX,10 y: event.clientY11 });12 };1314 return (15 <div style={{ height: '200px', border: '1px solid black' }} onMouseMove={handleMouseMove}>16 {/* 2. Call the render prop with the internal state */}17 {render(position)}18 </div>19 );20};2122// 3. Usage with different UIs23function App() {24 return (25 <div className="space-y-8 p-10">26 <h1 className="text-xl font-bold">Render Props Pattern</h1>2728 {/* UI 1: Simple Coordinates */}29 <MouseTracker render={({ x, y }) => (30 <p className="p-4">The mouse position is ({x}, {y})</p>31 )} />3233 {/* UI 2: A moving circle */}34 <MouseTracker render={({ x, y }) => (35 <div style={{36 position: 'absolute',37 backgroundColor: 'blue',38 borderRadius: '50%',39 left: x - 10,40 top: y - 10,41 width: '20px',42 height: '20px',43 pointerEvents: 'none'44 }} />45 )} />46 </div>47 );48}4950export default App;
🏋️ Practice Exercise
- Build a 'DataFetcher' component that takes a 'url' and a 'render' prop. The render prop should receive { data, loading, error }.
- Refactor a component that uses a Boolean 'isOpen' state to use a render prop (often called a 'Toggle' or 'Disclosure' component).
- Combine Render Props with Compound Components (e.g., a component that provides data via a render prop to its children).
- List 3 libraries you use that employ the render props pattern.
⚠️ Common Mistakes
Naming the prop something other than 'render' (it's a convention, not a rule, but consistency helps).
Not handling the case where the render function returns null.
Using Render Props when a simple Custom Hook would be cleaner (Hooks are generally preferred since 2019).
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Render Props