What are Higher Order Components?

Originally Posted December 14th 2016

If you spend much time at all reading through articles and documentation around React, you’re likely to run into the term “Higher Order component”, often abbreviated HoC. Since it is often used without context in React discussions, and is not a particularly intuitive term for many (most?) developers, I thought it was worth publishing a quick and simple explanation of what Higher Order Components are.

Higher Order Components are functions that take a React Component, and return a React Component. The “higher order” phrasing is borrowed from the term “higher order function”, a more widely used term in Mathematics and Computer Science that refers to a function that either takes one or more functions as an argument, returns a function, or does both. Since React Components can be thought of as functions that take data and return ui elements, the naming and usage make sense. Let’s look at an example of a higher order component.

This is a pretty basic HoC that takes a component and returns a new version of that component that will always be passed 2 extra props importantFunction and componentType. One is statically generated in this case, but the other is dynamically passed in when the component is generated. The ability to pass dynamic content in when defining the component is one of the key wins of HoCs in the real world. For instance, this is how Redux’s connect function works.

Note that this is different from a normal React Component that renders a subcomponent passed as an argument like this:

These 2 examples are roughly equivalent for this case, but accomplish things in different ways. The HoC is a function that takes a component and data when it is created and generates another component. The normal component example is a component that takes a component as a property and accesses a variable that is in its scope at creation time to generate the element tree that it renders. The HoC is more flexible as you could theoretically create multiple versions of a component using the single HoC.