Our WorkAbout UsOur ApproachThe Journal
Contact »
« Back to the journal
PHP, Javascript & React

React Higher-Order Components (HOC)


Mark Biek
Mark Biek

on 3/11/2019

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.


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.

Share to

Related Posts

What's the JAMstack?

By:Alec Robertson

As a front-end developer in 2020, it is time that I fulfill the FEDeral mandate that I publish words regarding the JAMStack. If you follow too many developers on Twitter, it’s likely you’ve heard about the Next Big Thing in web development, but I’d like to put this trend (fad? movement?) into context to better understand what’s truly new about this approach and whether it’s worth using.

Read More »
Recursive asynchronous calls with JavaScript and ES6

By:Mark Biek on 1/30/2018

ES6 generator functions make recursive asynchronous calls (relatively) easy.

Read More »