Middle+
What is HOC (Higher-Order Components)? What are they used for? Provide examples of using HOC in React.
sobes.tech AI
Answer from AI
HOC (Higher-Order Component) is a function in React that takes a component and returns a new component with extended or modified behavior.
The main goal of HOC is to reuse logic between components without duplication.
Example of usage:
// HOC that adds loading tracking logic
function withLoading(Component) {
return function WithLoadingComponent({ isLoading, ...props }) {
if (isLoading) return <div>Loading...</div>;
return <Component {...props} />;
};
}
// Regular component
function UserList({ users }) {
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
// Wrapping UserList with HOC
const UserListWithLoading = withLoading(UserList);
// Usage
// <UserListWithLoading isLoading={true} users={[]} />
HOCs are useful for:
- Adding state or logic (e.g., loading, authorization)
- Wrapping components in context or providers
- Logging or tracking
However, with the advent of hooks (React Hooks), many tasks previously solved with HOCs are now easier to implement using custom hooks.