Josué Hernández
When building dynamic and reusable user interfaces with React, developers often need strategies to share logic and compose complex components. Two popular patterns that facilitate this are Render Props and Composition. This blog will explore these patterns, provide real-world examples, and discuss their pros and cons.
A Render Prop is a technique for sharing code between React components using a prop whose value is a function. The function is then called to render dynamic content within the component.
A component that uses a Render Prop accepts a function as a prop and invokes it to render content dynamically. The function is often used to pass down data or provide shared behavior to child components.
import React, { useState } from 'react';
// A component that uses Render Props
const MouseTracker = ({ render }) => {
const [position, setPosition] = useState({ x: 0, y: 0 });
const handleMouseMove = (e) => {
setPosition({ x: e.clientX, y: e.clientY });
};
return (
<div style={{ height: '100vh' }} onMouseMove={handleMouseMove}>
{render(position)}
</div>
);
};
// Usage of MouseTracker with Render Props
const App = () => (
<MouseTracker
render={({ x, y }) => (
<h1>
Mouse Position: ({x}, {y})
</h1>
)}
/>
);
export default App;
✅ Pros:
❌ Cons:
Composition in React is a pattern where you build complex UIs by combining simpler components. Instead of relying on inheritance, React embraces composition to create component hierarchies.
Composition involves passing child components or elements as props to a parent component. This approach offers a flexible way to build dynamic UIs by nesting components.
import React from 'react';
// Parent component
const Card = ({ children }) => (
<div style={{ border: '1px solid #ddd', padding: '10px', borderRadius: '5px' }}>
{children}
</div>
);
// Using Composition
const App = () => (
<div>
<Card>
<h2>Title</h2>
<p>This is a paragraph inside the card component.</p>
</Card>
</div>
);
export default App;
✅ Pros:
❌ Cons:
Both Render Props and Composition are powerful patterns in React. The decision on which to use should be guided by the specific requirements of your application:
Future posts will explore other advanced patterns in React, such as Higher-Order Components (HOC) and the Provider Pattern, to help you build more robust and maintainable applications.