What are Higher-Order Components (HOCs)?
Higher-Order Component (HOC) is a function that takes a component and returns a
new component with additional props or behavior.
- Purpose: HOCs are used for code reuse, logic abstraction, and enhancing
components with common functionality (e.g., authentication, data fetching, etc.).
- How it works: HOCs are like decorators that wrap a component and add extra logic
before rendering the component.
Example:
function withLoading(Component) {
return function WithLoading(props) {
if (props.isLoading) {
return <div>Loading...</div>;
}
return <Component {...props} />;
};
}
const MyComponent = ({ data }) => <div>{data}</div>;
const MyComponentWithLoading = withLoading(MyComponent);
In this example, withLoading is a higher-order component that adds loading state to
MyComponent.