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

React Higher-Order Components (HOC)

By:

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.

giphy.gif

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:

2019-02-13-at-9.56.18-AM-300x242.png

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!

2019-02-13-at-10.16.42-AM-300x257.png

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

PHP, Javascript & React
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 »
Debugging a ReactJS Chrome Extension

By:Mark Biek on 3/5/2018

Simplify debugging your React-based Chrome Extension using the handy remote-redux-devtools library.

Read More »