Understanding React Higher-Order Components by Example

Build a React higher-order component step-by-step to understand how to implement the HOC pattern

Trey Huffine
Level Up Coding
Published in
5 min readMar 13, 2018

--

In this tutorial we will cover the concepts needed to build your own higher-order components (HOC). We will implement a HOC to save React state to localStorage, called withStorage, that will allow you to inject the functionality into components without needing to duplicate the logic across your entire application.

If you’re interested in seeing the same example in render props, check out this article

An introduction to HOC

A higher-order component in React is a pattern used to share common functionality between components without repeating code. A higher-order component is actually not a component though, it is a function. A HOC function takes a component as an argument and returns a component. It transforms a component into another component and adds additional data or functionality. In short:

const NewComponent = (BaseComponent) => {
// ... create new component from old one and update
return UpdatedComponent
}

Two HOC’s implementations that you may be familiar with in the React ecosystem are connect from Redux and withRouter from React Router. The connect function from Redux is used to give components access to the global state in the Redux store, and it passes these values to the component as props. The withRouter function injects the router information and functionality into the component, enabling the developer access or change the route.

Creating and maintaining a resume isn’t fun. Instead, let us generate an awesome CV for you :) Resume Builder >

--

--

Founder | Software Engineer. Building products that empower individuals.