By Rahul — Google Frontend Engineer
What is a HOC?
A Higher-Order Component is a function that takes a component and returns a new component with added behavior. It is a pattern, not a React API.
// A HOC that adds loading state
function withLoading(WrappedComponent) {
return function WithLoadingComponent({ isLoading, ...props }) {
if (isLoading) return <Spinner />;
return <WrappedComponent {...props} />;
};
}
// Usage
const UserListWithLoading = withLoading(UserList);
<UserListWithLoading isLoading={loading} users={users} />Real-World Examples
Authentication HOC
function withAuth(WrappedComponent) {
return function AuthComponent(props) {
const { user, loading } = useAuth();
if (loading) return <Spinner />;
if (!user) return <Redirect to="/login" />;
return <WrappedComponent {...props} user={user} />;
};
}
const ProtectedDashboard = withAuth(Dashboard);Analytics HOC
function withTracking(WrappedComponent, pageName) {
return function TrackedComponent(props) {
useEffect(() => {
analytics.track('page_view', { page: pageName });
}, []);
return <WrappedComponent {...props} />;
};
}
const TrackedCheckout = withTracking(Checkout, 'checkout');Problems with HOCs
- Wrapper hell:
withAuth(withTheme(withLoading(withRouter(Component))))— deeply nested, hard to debug - Prop collisions: Multiple HOCs might inject props with the same name
- Static methods lost: HOC does not copy static methods from the wrapped component
- Refs do not pass through: Need React.forwardRef to fix
HOCs vs Hooks (Modern Approach)
// HOC approach (old)
const EnhancedComponent = withAuth(withTheme(MyComponent));
// Hooks approach (modern — preferred)
function MyComponent() {
const { user } = useAuth();
const { theme } = useTheme();
if (!user) return <Redirect to="/login" />;
return <div style={{ color: theme.primary }}>...</div>;
}When HOCs Still Make Sense
- Wrapping class components (hooks only work in function components)
- Adding behavior that wraps the entire render (error boundaries, suspense boundaries)
- Third-party library integrations that provide HOCs
Summary
HOCs are functions that wrap components to add behavior. They were the primary code reuse pattern before hooks. Today, prefer custom hooks for shared logic. HOCs are still useful for render-wrapping patterns and class component support.