Render Props

Learn how to use the Render Props pattern to share logic between components in React.

1. What is Render Props?

The Render Props pattern involves passing a function as a prop to a component, allowing the parent component to control what is rendered.

const Component = ({ render }) => render();
                

Key Characteristics:

  • Enables sharing stateful logic between components.
  • Provides flexibility in rendering child components.

2. Example: Mouse Tracker

Here’s an example of using Render Props to track mouse coordinates:

import React, { useState } from 'react';

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

    const handleMouseMove = (event) => {
        setPosition({ x: event.clientX, y: event.clientY });
    };

    return (
        
{render(position)}
); } function App() { return ( (

Mouse Position: ({x}, {y})

)} /> ); } export default App;

Explanation: The MouseTracker component passes the mouse position to its child through a render prop.

3. Benefits of Render Props

  • Reusability: Share logic across multiple components.
  • Flexibility: Parent components can fully control rendering.
  • Clarity: Keeps the implementation and presentation separate.

4. Common Use Cases

  • Data Fetching: Use Render Props to share fetching logic.
  • State Management: Abstract common stateful logic into a Render Prop component.
  • Animations: Pass animation configurations through a Render Prop.

5. Alternatives to Render Props

React Hooks provide a simpler and more modern way to share logic:

import React, { useState } from 'react';

function useMousePosition() {
    const [position, setPosition] = useState({ x: 0, y: 0 });

    React.useEffect(() => {
        const handleMouseMove = (event) => {
            setPosition({ x: event.clientX, y: event.clientY });
        };

        window.addEventListener('mousemove', handleMouseMove);
        return () => window.removeEventListener('mousemove', handleMouseMove);
    }, []);

    return position;
}

function App() {
    const { x, y } = useMousePosition();

    return 

Mouse Position: ({x}, {y})

; } export default App;

Explanation: The custom hook useMousePosition replaces the need for a Render Prop component.

Additional Resources