Higher Order Components (HOCs) in React
What is an HOC?: Think of an HOC like a decorator for a Christmas tree.
The tree (your component) is great on its own, but you can add
decorations (HOCs) to give it extra flair or features without cutting
branches or changing the tree's basic structure.
How it works:
- Wrapper Around Your Tree (Component): An HOC wraps around your
original component, similar to tinsel wrapping around a tree. * Gifts Under Your Tree (Passing Props): The HOC can place additional
presents (props) under your tree for it to use.
Example: Imagine you have a basic Profile component that just displays
a user's name. But now, let's say we want to ensure the user is
logged in before showing the profile.
Instead of changing the Profile component directly, we can use an HOC
to handle this.
// This is our basic Profile component
function Profile(props) {
return <h1>{props.name}</h1>;
}
// This is our HOC to check if user is logged infunction withAuthentication(WrappedComponent) {
return function EnhancedComponent(props) {
if (props.isLoggedIn) {return &lt;WrappedComponent
{…props} />;
} else {
return <h2>Please log
in to view the profile.</h2>;
}
}
}
// Using our HOC
const AuthenticatedProfile = withAuthentication(Profile);
If you use AuthenticatedProfile and the user is logged in (i.e.,
isLoggedIn prop is true), they'll see their name. If not,
they'll get a message asking them to log in.
Why is this cool?:
- Reuse: If we have other components that need similar authentication
checks, we can reuse our withAuthentication HOC. * Clean Code: Our original Profile component remains simple and does
one thing: shows the user's name.