What is a higher order component in React?
Short answer
A higher order component, often shortened to HOC, is a function that takes a component as input and returns a new, enhanced component with extra behavior added, without changing the original component's own code.
Advertisement
AModel answer
A higher order component, often shortened to HOC, is a function that takes a component as input and returns a new, enhanced component with extra behavior added, without changing the original component's own code.
function withLoading(WrappedComponent) {
return function EnhancedComponent({ isLoading, ...props }) {
if (isLoading) return <p>Loading</p>;
return <WrappedComponent {...props} />;
};
}
const ProductListWithLoading = withLoading(ProductList);Real-world example
A team wraps several different components with the same withLoading higher order component, giving each one the exact same loading spinner behavior without repeating that logic inside every single component.
Likely follow-ups
- How has the popularity of higher order components changed since custom hooks were introduced?
- What naming convention is commonly used for higher order components?
Related topics