React / 58
Higher-order components
A function that takes a component and returns a new, enhanced one. Still handy for wrapping UI, but hooks replaced most of its old jobs.
A function that makes components
A higher-order component (HOC) is a plain function: you pass in a component, and it returns a new one. The name comes from higher-order functions in JavaScript (like map), which take or return other functions.
in · a component
RestaurantCard
Tasty Bites
South Indian · 4.5★ · 25 min
out · a new component
PromotedRestaurantCard
Tasty Bites
South Indian · 4.5★ · 25 min
Build withPromotedLabel
export function withPromotedLabel(Card) {
return function PromotedCard(props) {
return (
<div className="relative">
<span className="absolute -top-2 left-2 rounded bg-black px-2 text-xs text-white">
Promoted
</span>
<Card {...props} />
</div>
);
};
}Three things to notice:
- The name starts with
with. That's the convention, so readers know it's an HOC. - It returns a component (a function that returns JSX), not JSX.
{...props}passes every prop straight through, so the original card gets its data.
Use it
import { RestaurantCard } from "./RestaurantCard";
import { withPromotedLabel } from "./withPromotedLabel";
const PromotedRestaurantCard = withPromotedLabel(RestaurantCard);
export function RestaurantList({ restaurants }) {
return (
<div className="grid gap-4">
{restaurants.map((r) =>
r.promoted ? (
<PromotedRestaurantCard key={r.id} restaurant={r} />
) : (
<RestaurantCard key={r.id} restaurant={r} />
)
)}
</div>
);
}withPromotedLabel runs once, when the file loads, and the result is used like any other component.
Why hooks replaced most HOCs
Before hooks (2019), HOCs were the main way to share logic: withRouter gave you the URL, connect() from Redux gave you store data, withAuth gave you the user. Each one added props from somewhere you couldn't see. Stack three and you had "wrapper hell", plus props that could silently overwrite each other.
Custom hooks do the same job more plainly:
function StatusBar({ isOnline }) { // where does isOnline come from?
return <p>{isOnline ? "Online" : "Offline"}</p>;
}
export default withOnlineStatus(StatusBar);function StatusBar() {
const isOnline = useOnlineStatus(); // you can see exactly where
return <p>{isOnline ? "Online" : "Offline"}</p>;
}
export default StatusBar;So: share logic with a hook. Use an HOC when you want to wrap the rendered UI, like a label, a layout, a permission check, or an error boundary around a component. You'll also meet HOC-style APIs in React itself: memo(Component) takes a component and returns an optimised one.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
