Higher-Order Components in React

Higher-order components are wrapper components that provide a certain level of abstraction for a specific component behaviour. They make it easy to reuse the component logic.

In practical terms, it is simply a function that takes other components as parameters and returns a new wrapped component that can render the original component with the intended new behaviour. Here’s how a simple HOC function call looks like:

const wrappedComponent = hoc(component);

You tend to this been used in several popular implementations like Redux’s connect, React Router’s withRouter and Material-UI’s withStyles. It is all based on the idea of the don’t-repeat-yourself (DRY) principle and if one can imagine the possible layers of composition this can bring to a React component, you’d see why its widely accepted and used.

Here’s an example of a component that is wrapped by a HOC:

import React from 'react';

const hoc = (component, props) => {
   class WrappedComponent extends React.Component {
      render() {
         return <component {...props} />;
      }
   }
   return WrappedComponent;
}

So you can see in the example above that the WrappedComponent is augmented with some extra props which obviously could lead to a new behaviour of the component.

HOCs are mostly used in cases like:

  • Showing a loader while component is requesting data (WithLoading)
  • Conditionally rendering a component (WithAuth)
  • Provide a component with specific styling (WithStyling)
  • Provide a component with any prop you want (WithNameChange)

If you noticed by now, HOCs are usually named with a prefix of with, so whenever you look at any React codebase, watch out for this naming convention, it will make easy for you to spot HOCs in code.

I hope you found this article on HOCs quite helpful, there will be another follow up article where we dive deeper into how you can build HOCs in React for one or two of the use cases mentioned above and see them in action.

Please drop your comments or questions below if you have any questions, I will endeavour to answer them.

Leave a Reply

Your email address will not be published. Required fields are marked *