What are Higher-Order Components (HOC)?
A Higher-Order Component (HOC) is a function that takes a component and returns a new component, wrapping it with extra behavior. A pattern for sharing reusable logic across multiple components.
Common uses — auth gates (
withAuth), connect Redux state (connect), feature flags, theming, logging.Pure function — doesn't mutate the input component; returns a new wrapped one.
Pass-through props — spread
...propsso the wrapped component receives everything plus the new behavior.Naming convention — prefix with
with(withRouter,withTheme) so the pattern is recognizable.Modern alternative — custom hooks are usually clearer; HOCs survive in legacy code and a few libraries (Redux
connect, react-router v5).Drawback — can create deep wrapper trees that are hard to debug.
// HOC that adds loading state
function withLoading(WrappedComponent) {
return function WithLoadingComponent({ isLoading, ...props }) {
if (isLoading) return <div>Loading...</div>;
return <WrappedComponent {...props} />;
};
}
// Usage
const UserListWithLoading = withLoading(UserList);
<UserListWithLoading isLoading={true} users={users} />
// HOC for authentication
function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
const { user } = useAuth();
if (!user) return <Navigate to="/login" />;
return <WrappedComponent {...props} user={user} />;
};
}
const ProtectedDashboard = withAuth(Dashboard);
// Modern alternative: Custom Hook
function useAuth() {
const { user } = useContext(AuthContext);
return { user, isAuthenticated: !!user };
}withLoading wraps any component with loading logic. withAuth wraps any component with authentication checks. Both follow the pattern: accept a component, return a new component with added behavior, pass through all props.
The custom hook alternative (useAuth) achieves the same goal without wrapping.
Know the HOC pattern and its conventions (with* naming, prop passing). But also mention that custom Hooks are the modern alternative.
Showing both and explaining when each is appropriate demonstrates evolution awareness.