Using React Higher-Order Component to avoid repeating yourself

Vix Nguyen
3 min readJul 1, 2020

During my years in frontend development, I always try to find and apply best practices for every JavaScript framework/library I work on. And the idea to write this article originally came from my Angular topic:

On the topic above, we discussed how to control the content based on user status, about the DRY principle. Finally, I provided a solution to solve that issue by using Structural Directives.

Following the same line of thought, but let’s go forward to the other case study that is regularly required for good user experience, apply the same logic for each page request like this:

Higher-order component
  • Show loading spinner while data processing/API fetching.
  • Display results in case data are present (Article list).
  • Display a message to tell users that an error occurred with their request (Article detail).

Likely, you’re going to do the same checks in both article list and article detail components and you’ll repeat yourself a lot. That’s a not good idea since React provides us an advanced technique for reusing component logic that is HOC.

What’s HOC?

HOC stands for Higher-order component, which is a function that takes a React component and returns a new React component.

Create a HOC

Let’s create a pageRenderer to check page state then display contents accordingly.

This HOC is written in React functional component

Usage

Define a presentation component named PageContentTpl that refers to the Wrapped component in pageRenderer:

Use pageRenderer and PageContentTpl inside ArticleList container component:

Do the same with ArticleDetail

Emulate the real work with the sample data flow:

This is the complete version of the ArticleList component:

Those are simple steps to create and use a HOC for page requesting. Just write your code to handle a specific logic only once time, and use this anywhere if it has the same duty.

Advances

For easy to understand, in the example above, I had defined sample data flow inside ArticleList component and passed props through PageContent, however, in fact, you can absolutely use react hocks inside a HOC to connect to a Redux store, work with actions, reducers… like this:

Higher-order component with Hocks
Your component is now getting simpler

Please take a look at my repository for more detail.

References

The pageRenderer is written in React functional component, you can check out to React official document to have a comparison of how it looks like in the class component. You also need to read about the convention for using a HOC and further information there.

Hope this helps with your work. Thanks for reading!

--

--

Vix Nguyen

Work as a Technical Manager, I would love to contribute more to the IT industry, help people to make their business successful with IT solutions