As React apps scale, you’ll need to construction elements for better reusability and composability. Listed below are some highly effective React patterns:
Compound Elements
The compound elements sample creates part APIs with shared context:
// Dad or mum exposes context via 'Field' part
perform Format({kids}) {
return <Field>{kids}</Field>
}
// Youngsters entry shared context by way of Field
perform Profile() {
return (
<Format>
<Field p={2}>
<h1>Jane Doe</h1>
</Field>
</Format>
);
}
This gives extra versatile APIs than simply props.
Render Props
With render props, elements settle for a perform prop that returns a React component:
// Render prop part
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
The next-order part (HOC) wraps a part to boost it:
// HOC that handles logic
perform withAuth(Element) {
return props => (
<Element {...props} />
);
}
// Enhanced part
perform ProfilePage() {
return <h1>Personal Profile</h1>;
}
export default withAuth(ProfilePage);
HOCs present separation of issues for part logic.
Abstract
- Compound elements present context via shared elements
- Render props permit elements to find out rendering
- HOCs improve part logic by wrapping elements
These patterns unlock highly effective strategies for reusable, configurable React elements.