As React apps scale, you’ll wish to construction elements for better reusability and composability. Listed here are some highly effective React patterns:
Compound Parts
The compound elements sample creates element APIs with shared context:
// Dad or mum exposes context via 'Field' element
operate Format({kids}) {
return <Field>{kids}</Field>
}
// Kids entry shared context through Field
operate 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, elements settle for a operate prop that returns a React component:
// Render prop element
operate 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 Parts
A better-order element (HOC) wraps a element to reinforce it:
// HOC that handles logic
operate withAuth(Part) {
return props => (
<Part {...props} />
);
}
// Enhanced element
operate ProfilePage() {
return <h1>Non-public Profile</h1>;
}
export default withAuth(ProfilePage);
HOCs present separation of issues for element logic.
Abstract
- Compound elements present context via shared elements
- Render props enable elements to find out rendering
- HOCs improve element logic by wrapping elements
These patterns unlock highly effective methods for reusable, configurable React elements.