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.
Real-World Examples
Authentication HOC
Analytics HOC
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)
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.