Higher-Order Components in React
1. Introduction
Higher-Order Components (HOCs) are a powerful pattern in React that allow for the reuse of component logic. They are functions that take a component and return a new component, enhancing it with additional functionality.
2. Definition
A Higher-Order Component is a function that takes a component as an argument and returns a new component. The HOC pattern can be used for code reuse, rendering manipulation, and props manipulation.
3. Usage
To create a Higher-Order Component, define a function that takes a component and returns a new component:
function withEnhancement(WrappedComponent) {
return function EnhancedComponent(props) {
// Add extra props or behavior here
return ;
};
}
4. Examples
Here’s an example of a Higher-Order Component that adds loading functionality:
import React from 'react';
function withLoading(Component) {
return function LoadingComponent({ isLoading, ...props }) {
if (isLoading) {
return Loading...;
}
return ;
};
}
// Example usage
const MyComponent = ({ data }) => {data};
const MyComponentWithLoading = withLoading(MyComponent);
5. Best Practices
- HOCs should not modify the original component.
- Use display names for debugging:
EnhancedComponent.displayName = `WithHOC(${getDisplayName(WrappedComponent)})`;
- Ensure HOCs are pure functions; they should not have side effects.
6. FAQ
What are common use cases for HOCs?
Common use cases include handling authentication, data fetching, and adding routing capabilities to components.
Can you use multiple HOCs on a single component?
Yes, you can compose multiple HOCs to enhance a single component with various functionalities.