Skip to main content

Render Props in React

Definition

Render Props is a pattern where a component receives a function as its child, which returns JSX. The component then calls this function to determine what to render.

Example

Here's a correct example of the Render Props pattern:

import React, { useState } from "react";

// Component using Render Props
const Counter = ({ children }) => {
const [count, setCount] = useState(0);

const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);

return children(count, increment, decrement);
};

// Usage
const App = () => (
<Counter>
{(count, increment, decrement) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
)}
</Counter>
);

export default App;

How it works

  1. The Counter component receives a function as its children prop.
  2. Inside Counter, we call this function, passing it the state and methods as arguments.
  3. The function returns JSX, which becomes the rendered output of Counter.
  4. In the usage, we pass a function as the child of Counter, which receives the state and methods and returns the desired JSX.

This pattern allows for flexible and reusable components by separating the logic (in Counter) from the presentation (in the function passed to Counter).

Pros and Cons

Pros

  1. Highly flexible
  2. Clear separation of concerns
  3. Avoids prop drilling
  4. Reusable logic

Cons

  1. Can be confusing at first
  2. Potential for callback hell in complex scenarios
  3. May impact performance if not memoized properly

Conclusion

Render Props is a powerful pattern for creating flexible and reusable components in React. It's particularly useful when you need to share behavior between components while allowing for custom rendering.