As React apps scale, you’ll need to construction elements for higher reusability and composability. Listed below are some highly effective React patterns:
Compound Elements
The compound elements sample creates element APIs with shared context:
// Mother or father exposes context by way of 'Field' element
perform Structure({youngsters}) {
return <Field>{youngsters}</Field>
}
// Kids entry shared context through Field
perform Profile() {
return (
<Structure>
<Field p={2}>
<h1>Jane Doe</h1>
</Field>
</Structure>
);
}
This offers extra versatile APIs than simply props.
Render Props
With render props, elements settle for a perform prop that returns a React ingredient:
// Render prop element
perform Mouse({ render }) {
return render(mousePosition);
}
// Utilization
<Mouse
render={place => (
<h1>The mouse place is {place.x}, {place.y}</h1>
)}
/>
This permits elements to dynamically decide what ought to render.
Increased-Order Elements
A better-order element (HOC) wraps a element to boost it:
// HOC that handles logic
perform withAuth(Element) {
return props => (
<Element {...props} />
);
}
// Enhanced element
perform ProfilePage() {
return <h1>Personal Profile</h1>;
}
export default withAuth(ProfilePage);
HOCs present separation of considerations for element logic.
Abstract
- Compound elements present context by way of shared elements
- Render props permit elements to find out rendering
- HOCs improve element logic by wrapping elements
These patterns unlock highly effective strategies for reusable, configurable React elements.