How to Use React Higher-Order Components
Utilise React HOCs for class and functional components
Higher-Order Components (or HOCs) in React are functions that take a component and return a new component, enhancing the original in some way:
const EnhancedComponent = hoc(OriginalComponent);
HOCs are very useful for injecting functions, state, and additional data into components as props, as well as wrapping components with styling or more JSX. Using HOCs allow us to only extend the components that need to be extended, while at the same time keeping your codebase modular by separating specialised logic from component implementations.
Remember, React components are designed to be reusable — they should have one purpose and only contain the logic needed for that purpose. HOCs allow us to adhere to these expectations.
This article will break down what HOCs are and how they are used in React, with examples of how they can be applied.
HOCs at a High Level
You will find many modules adopting the HOC design pattern as a means of injecting functionality from the module into your components — this has proven to be the most popular use case of HOCs.