HOC (Higher-Order Component) is a function that takes a component and returns a new component with additional capabilities.
Simple analogy: Imagine you are buying a regular t-shirt (component). HOC is a workshop that:
What it looks like:
1// HOC for authorization check2function withAuth(WrappedComponent) {3 return function EnhancedComponent(props) {4 if (!props.isLoggedIn) {5 return <LoginPage />;6 }7 return <WrappedComponent {...props} />;8 };9}1011// Usage12const AdminPanelWithAuth = withAuth(AdminPanel);13<AdminPanelWithAuth isLoggedIn={false} /> // Will show LoginPage
Popular HOC examples:
withRouter — adds router props (old React Router).connect (Redux) — connects component to Redux store.withStyles (Material UI) — adds styles.HOC disadvantages:
Modern alternative — custom hooks. Instead of withAuth(Component) it is better to make useAuth().
Why it matters: HOCs were the primary pattern for code reuse in React before hooks. Understanding them helps maintain legacy codebases and understand library APIs like Redux connect().
Common mistake: Not forwarding displayName in HOCs, making debugging harder. Always set EnhancedComponent.displayName = "withAuth(AdminPanel)".