Higher-Order Components in React?
If you’ve ever considered it repetitive and cumbersome writing the same logic or having to fetch data in different components, then this article is for you. These problems are some of the basic challenges faced by React developers but can be solved using higher-order components.
One key use of HOC is that it allows you to abstract out the common functionalities of a component and build a function. With HOC, you can share logic across different components without having to rewrite it. HOC amplifies one of the best-known principles of programming called the don’t-repeat-yourself (DRY) principle, a very important principle to adhere to generally when writing code or building an application.
In this tutorial, we will start by looking at Higher-Order Components in React from a high level- what they are, why you should use them, and how to write yours. We will also cover different use cases with real-life examples alongside a few caveats or a few things to avoid when using higher-order components.
What is Higher-Order Component- HOC?
Higher-Order Component in React is a function that takes a component as an argument and returns a new component. It is the state-of-the-art technique in React for reusing component logic. The HOC adds additional data or functionality to an original component. These components are not part of the React API, but a pattern that comes to the fore from React’s compositional nature. In simple code it looks something like this:
Here, the function called higherOrderComponent
that takes an argument- originalComponent
. higherOrderComponent
is a HOC component that adds some additional functionality to originalComponent
and returns a new component. In addition, the NewComponent
can also be referred to as EnhancedComponent
like so:
Here’s HOC in simple terms:
- It is a component
- It takes two arguments. The first argument is a component in which we want to add logic, and the second argument is data
- Then it returns a new component
- The returned component is the enhanced version of the component that we have passed.