If you are working on a React application, you might have already come across the term Higher-Order Component, commonly known as HOC. It’s one of the useful patterns in React that helps you organize and reuse logic more efficiently. In this post, I’ll walk you through what an HOC actually is and how you can use it in your own project.
What is Higher Order Component or HOC ?
Whenever you have a piece of functionality that needs to be shared across multiple components, that’s where an HOC becomes handy. An HOC is basically a function that takes a component as input, wraps it, and returns a new component with added behavior.
So what kind of “additional capabilities” can an HOC provide? Here are some real-world examples:
- Adding UI states like loading/error
- Adding Authorization logic
- Handling caching
- Injecting props
- Subscribing to events
- Fetching data
By wrapping your component inside an HOC, you keep your original component clean and focused only on UI, while the shared logic stays in one place.
Steps to implement HOC
Step 1: Create the HOC
const withLoader = (WrappedComponent) => {
return function WithLoaderComponent({ isLoading, ...props }) {
if (isLoading) return <div>Loading...</div>;
return <WrappedComponent {...props} />;
};
};Step 2: Use it in a Component
const UserList = ({ users }) => {
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
};
const UserListWithLoader = withLoader(UserList);Step 3: Render it
<UserListWithLoader isLoading={true} users={[]} />That is it. Now you can use this withLoader HOC for all of your components as shown in Step 2 & 3.
Q. One of the obvious question may come to your mind is where to put this HOC ?
A. Since you may have more than one HOCs and it represents a common functinality across multiple components, I would generally prefer to create a seaprate folder for the HOCs as shown below:
src/
components/
hoc/
withLoader.js
withAuth.js
withLgger.js
pages/
App.js