A Higher Order Component (HOC) is a technique in React that enables code reuse.
It is a function that takes an existing component as an argument(input) and returns a new component.
This new component "wraps" the original component and can add extra features, such as props or state, to the wrapped component.
Let's take an example,
function higherOrderComponent(WrappedComponent) {
return (props) => {
return <WrappedComponent {...props} />;
}
}
const Component = (props) => {
return (<h1>Hello {props.name}!</h1>)
};
const NewComponent = higherOrderComponent(Component);
const element = <NewComponent name="React" />;
Let's understand the code
In the above example, higherOrderComponent takes a Component as an argument and returns a new component. Here higherOrderComponent is reusing the Component.
Higher-order function are used in the following scenarios:
Authentication: It can be used to wrap components and provide the authentication state as a prop. This allows you to abstract away the authentication logic and reuse it across multiple components.
Authorization: HOCs can also be used to implement authorization, i.e. determining whether a user has permission to access a certain resource.
Data Fetching: HOCs can be used to fetch data and pass it down as props to the wrapped component. This allows you to abstract away the data-fetching logic and reuse it across multiple components.
UI Theme: HOCs can be used to implement a UI theme, by wrapping components and passing down theme-related props. This allows you to easily change the theme by swapping the HOC.
Code Splitting: HOCs can be used to implement code splitting, by wrapping components and loading the wrapped component lazily. This allows you to optimize the performance of your application by only loading the code that's needed.