Skip to content

Latest commit

 

History

History
127 lines (89 loc) · 2.87 KB

File metadata and controls

127 lines (89 loc) · 2.87 KB

Render Props

Definition

A render prop is a technique in React where a component accepts a function as a prop, and uses that function to determine what to render. The key idea: Instead of rendering its own UI, the component delegates rendering to a function provided by the parent.

In short: It’s a pattern for sharing stateful logic between components using a function prop.


Why It Exists

Before Hooks (pre–React 16.8), the main ways to share logic were:

  • HOCs (Higher-Order Components) — wrapping components
  • Render Props — passing a function that returns UI

Render props solved the code reuse problem without deep inheritance.


Basic Example

// DataProvider.js
import { useState, useEffect } from 'react';

function DataProvider({ render }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/data')
      .then((res) => res.json())
      .then(setData);
  }, []);

  return render(data); // calling the render prop
}

export default DataProvider;
// App.js
<DataProvider
  render={(data) => (
    <div>{data ? <p>{data.message}</p> : <p>Loading...</p>}</div>
  )}
/>

Here:

  • DataProvider handles the logic (fetching data).
  • The parent decides how to display that data.

Common Usage

  • Sharing logic without HOCs
  • Conditional rendering flexibility
  • Reusable logic for UI variations (tooltips, modals, mouse tracking)

Example: Mouse Tracker

class MouseTracker extends React.Component {
  state = { x: 0, y: 0 };

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

  render() {
    return (
      <div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)} {/* render prop */}
      </div>
    );
  }
}

// Usage
<MouseTracker
  render={({ x, y }) => (
    <h1>
      The mouse is at ({x}, {y})
    </h1>
  )}
/>;

Pros & Cons

Pros

  • Reusable and composable logic
  • Avoids “wrapper hell” from too many HOCs
  • Full control over UI from the consumer side

⚠️ Cons

  • Verbose syntax
  • Can lead to deeply nested JSX if overused
  • Mostly replaced by custom hooks in modern React

Interview Tips

  • Mention that Hooks largely replaced Render Props for logic sharing, but render props are still valid and appear in older codebases.
  • Compare briefly with HOCs:
    • HOCs wrap components; render props pass a function.
    • Render props give more explicit control of rendering.
  • You may get a question like:

    “Why use render props over HOCs?” Answer: More flexibility, avoids naming collisions in props, avoids extra component layers.


One-liner Summary for Interviews

A render prop is a technique for sharing component logic by passing a function that returns UI, giving the parent full control over rendering while the child handles the logic.