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