React Web Project Building. Part 2 — HOCs

Evheniy Bystrov
HackerNoon.com
5 min readNov 20, 2018

--

In previous part we created AppKernel HOC (higher-order component) to add some useful features for your app.

In this part we will continue work with HOCs and functional programming. We will split our big HOC into some small parts which you can reuse to build your own app HOC with only useful parts.

But before we start, we need to remember some functional programming basics.

HOC (higher-order component) is a kind of higher-order function. It’s a function which has component as an argument and it returns a new component.

In this part we will use functional composition and some kind of curry.

Let’s remember our AppKernel from the pervious part:

And just imagine our goal:

It looks more declarative — less code with the same functionality. And other benefit — you can compose any part in the HOC and reuse it in any other React app.

Who wants to see all code now, I created a github repository.

So, let’s start form the beginning.

First of all, we need to create compose function. For this I created a helper inside of our src/app directory. I didn’t created own compose function because we use redux, it has own compose function and it works perfect for us.

The main idea is making small HOCs for each layer. For this I created a wrapper:

It gets WrapperComponent like StrictMode or Suspense and wraps the Component. We can add any property if we need it, for example if we need to pass store in Redux Provider:

But to use it in composition we need to curry this function:

It’s uses wrapper function with some checking: if we didn’t put the Component it returns another function.

And all code of our helper:

Now we are ready to create a HOC for each layer.

StrictMode

src/app/hocs/strictMode.js:

It’s too easy. We create a HOC from the React StrictMode component using our hocCreator helper function.

If we imagine how it works we get something like this:

ErrorBoundary

src/app/hocs/errorBoundary.js:

Here we can see how I use properties for ErrorBoundary component.

It works like this:

Redux

src/app/hocs/redux.js:

Router

src/app/hocs/router.js:

Suspense

src/app/hocs/suspense.js:

And small bonus. I updated our page component to use only pure components. Pure components use the same idea like pure functions — no side effects.

It’s function with props arguments and it returns JSX:

props => JSX

src/page/index.js:

--

--

Evheniy Bystrov
HackerNoon.com

I can help with IT infrastructure (AWS), apps (Node.js + React) and teams.