Higher-Order Components (HOCs)
Higher-Order Components (HOCs) are a way to reuse component logic. They are a pattern in React that allow you to share common functionality between components without having to repeat the same code in multiple places.
To create a Higher-Order Component, you need to create a new function that will take an existing component as an argument and return a new component that wraps it. The new component will have access to the props of the original component and can add additional functionality to it.
Here is an example of a HOC that adds a new prop to a component:
import React from 'react';
const withNewProp = (WrappedComponent) => {
return (props) => {
return <WrappedComponent {...props} newProp="Hello World" />
}
}
export default withNewProp;
In this example, withNewProp
is a HOC that takes a component as an argument and returns a new component that wraps it. The new component will have a new prop newProp
with the value "Hello World".
To use this HOC, you need to import it and use it to wrap your component.
import withNewProp from './withNewProp';
const MyComponent = (props) => {
return <h1>{props.newProp}</h1>;
}
export default withNewProp(MyComponent);
In this example, MyComponent
is wrapped with the withNewProp
HOC. The MyComponent
will now have access to the new prop newProp
with the value "Hello World".
It's worth noting that HOCs can also be used to add additional functionality such as authentication, data fetching, or performance optimization.
You can also chain multiple HOCs together to add multiple functionalities to a component.
export default withNewProp1(withNewProp2(MyComponent));
Please note that when you use HOCs, it's important to consider the performance impact, as it can cause unnecessary re-renders in your application.