PHP, Javascript & React

React Higher-Order Components (HOC)

By:

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

Wordpress to Sanity Data Script

By:Nick Stewart on 3/11/2021

One of the biggest challenges of moving from one CMS to another is getting your existing data to the new platform. In our case, we were moving our existing WordPress platform, which had been around for years, over to the Sanity.io platform.

Read More »
Developing the New via.studio

By:Alec Robertson on 6/14/2021

A deep dive into creating a fast, user-focused experience on the latest web technology stack for the new via.studio website.

Read More »