Q18: What is a Higher-Order Component (HOC) and how does it compare to Render Props?
A Higher-Order Component is a pure function that takes a component as an argument and returns an enhanced new component (const EnhancedComp = withFeature(WrappedComp)). Render Props passes a render function prop to delegate UI rendering. Both patterns share component logic, though Custom Hooks have largely superseded them.
HOC Wrapper Pattern
function withAuthentication(WrappedComponent) {
return function AuthenticatedComponent(props) {
const { isAuthenticated } = useAuth();
if (!isAuthenticated) return <p>Access Denied</p>;
return <WrappedComponent {...props} />;
};
}💡 withAuthentication wraps components with auth authorization checks before rendering child components.
Key Takeaways
- HOC:
Component => EnhancedComponentpattern. - Avoid mutating original wrapped components; pass unhandled props through.
Knowledge Check
What common issue can occur when chaining multiple HOC wrappers together?