javascript / intermediate
Snippet
Sharing Logic via Render Props
The Render Props pattern involves passing a function as a prop to a component. This function tells the component what to render, allowing you to share stateful logic (like mouse tracking) without hardcoding the UI structure.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const MouseTracker = ({ render }) => {const [pos, setPos] = useState({ x: 0, y: 0 });const handleMove = (e) => setPos({ x: e.clientX, y: e.clientY });return (<div style={{ height: '100vh' }} onMouseMove={handleMove}>{render(pos)}</div>);};// Usage<MouseTracker render={({ x, y }) => (<h1>The mouse position is ({x}, {y})</h1>)} />
react
Breakdown
1
const MouseTracker = ({ render }) => {
Defines a component that expects a function named 'render' as a prop.
2
{render(pos)}
Calls the passed function with the current internal state to determine the output.