Higher-Order Components
19 January, 2023
0
0
0
Contributors
What is the HOC design pattern
In React, a Higher-Order Component (HOC) is a design pattern that allows you to reuse component logic. It is a function that takes a component as an argument and returns a new component that has some additional functionality or behavior.
What is the use?
The HOC pattern allows you to abstract away common functionality that is shared across multiple components, and encapsulate it in a reusable, standalone component. For example, you could create an HOC that adds a loading indicator to a component, and use that HOC to add a loading indicator to any component that needs it.
An example of the HOC design pattern
Here's an example of a simple HOC that adds a loading indicator to a component:
import React, { useState } from 'react';
function withLoadingIndicator(WrappedComponent) {
return function LoadingIndicator(props) {
const [isLoading, setIsLoading] = useState(false);
return (
<>
{isLoading && <div>Loading...</div>}
<WrappedComponent {...props} setIsLoading={setIsLoading} />
</>
);
}
}
export default withLoadingIndicator;
To use this HOC, you would import it and wrap the component that you want to add a loading indicator to:
import withLoadingIndicator from './withLoadingIndicator';
function MyComponent() {
// ...
}
export default withLoadingIndicator(MyComponent);
This HOC takes a component as an argument, and returns a new component that renders the original component along with a loading indicator. The component that receives the loading indicator is wrapped component, this component is passed a prop setIsLoading
that allows the wrapped component to toggle the loading state.
In this example the HOC is using the state and the setIsLoading
method to handle the state of the loading, but the HOC could also handle the state of the loading indicator, a simple example but the HOC pattern can be use to handle authentication, authorization, data fetching, logging, and many other tasks.
Summary
HOCs are a powerful feature that allows you to reuse component logic, create more reusable components and make your codebase more maintainable, while still allowing you to write reusable and composable UI components.