Higher-Order Components
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.
Definition
Higher Order Component (HOC): an abstraction over a component. When given a component (and perhaps some other parameters), they return a new component.
From the perspective of the JavaScript language:
- a higher-order component is a function that takes a component and returns a new component.
Simple HOC
- Here is a simple example of a higher-order component (HOC). Paste the code below in
main.js
Composition vs. HOCs
- To better understand when to use HOCs it is helpful to compare them to using composition with components. Paste the code below in
main.js
to see how composition can be used to combine components.
The downside of this approach is that a new component needs to get created for each suffix. This is not a problem in the example above because the components are simple (one line) but as components become more complex this can become more onerous.
- Using a Higher-order component (function)
The wrapper
function is the higher-order function or more specifically higher-order component in the code below.
Another Example
Use Cases
Cross-Cutting Concerns
- When you have the need to share the state or behavior that one component encapsulates to other components that need that same state
- Repeated Logic
- Render table, given data in an Array
- Show tooltip on hover of multiple components
- Adding additional props
- Decorating
- You can often get the same reuse out of your code using any of the following techniques
- Higher-Order Components
- Render Props
- Custom Hooks
Conventions
- Don’t Mutate the Original Component. Use Composition. (prototype)
- Convention: Pass Unrelated Props Through to the Wrapped Component
- Convention: Wrap the Display Name for Easy Debugging