Higher-Order Components (HOCs) are functions that take a component and return a new enhanced component.
Basic HOC#
HOC with Configuration#
Injecting Props#
Display Name#
Forwarding Refs#
Composing HOCs#
Static Methods#
Error Boundary HOC#
Data Fetching HOC#
Conditional Rendering HOC#
HOCs vs Hooks#
Best Practices#
HOC Design:
✓ Pass through unrelated props
✓ Set displayName for debugging
✓ Forward refs when needed
✓ Copy static methods
Naming:
✓ Use 'with' prefix (withAuth, withData)
✓ Descriptive names
✓ Match injected prop names
Performance:
✓ Don't create HOCs inside render
✓ Memoize when appropriate
✓ Avoid unnecessary re-renders
Avoid:
✗ Mutating the original component
✗ Using HOCs inside render method
✗ HOC inside another HOC definition
✗ Over-nesting HOCs
Conclusion#
Higher-Order Components provide a powerful pattern for reusing component logic. They wrap components to inject props, handle authentication, add error boundaries, and more. While hooks have replaced many HOC use cases, HOCs remain valuable for class components and certain composition patterns. Use compose for combining multiple HOCs, remember to forward refs and copy static methods, and consider hooks as a simpler alternative for functional components.