Hey there! You're using an out-of-date browser, so this site probably looks pretty funny. Upgrade your browser for the full experience.

React Higher-Order Components (HOC)

What is a higher-order component in React?

The official definition is:

A higher-order component is a function that takes a component and returns a new component. Whereas a component transforms props into UI, a higher-order component transforms a component into another component.

Confused Pug Dog

But what does that actually mean? And, more importantly, what can we use a HOC for?

The simplest way to explain it is that a HOC lets you share functionality across multiple components.

Let’s look at a simple example. (Full example source code here: https://github.com/markbiek/react-higher-order-component)

In the above, we have a simple React app which renders an SVG that looks like this:

The <Circle /> and <Rect /> components handle rendering the actual SVG elements while receiving the stroke, stroke-width, and fill color from the App component.

Now let’s say we wanted to do something when we mouseover each of those components. Without an HOC, we’d have to implement the same internal state and event handling functions in both <Circle /> and <Rect />. That’s a lot of code duplication!

Or we can write an HOC that keeps all of the mouseover functionality in one place and use that to extend our components.

(Take a look at the comments in 👆 for details about what it’s doing.)

Now we have to make some minor tweaks to <Circle /> and <Rect />.

You’ll notice that we’re now passing the enter and leave event handlers to the onMouseEnter and onMouseLeave events.

But the most important change is export default withHover(Circle);.

Instead of exporting the actual component, we export the wrapped component. As far as our App component is concerned, it’s still the same Circle. But, behind the scenes, our Circle component is now imbued with extra hovering functionality!

Obviously, this is a contrived example. But I hope it clears up some of the mystique behind HOCs and shows you might be able to use them in your own apps.

Born and raised in
Louisville, Kentucky.


223 S. Clay St

Work With Us

  • This field is for validation purposes and should be left unchanged.