Higher order components (HOC) are a great pattern to pull-up reusable code across components to a higher level and reuse it wherever needed. Quoting the purpose of HOC from the React official docs:

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. Concretely, a higher-order component is a function that takes a component and returns a new component.

As such, HOCs are a great way to leverage React’s compositional nature to avoid duplicate code and make it easier to develop and maintain your apps.

Why? because instead of duplicating code, we’ll turn into a building blocks which can be shared in multiple places in a controlled way, while changes can be easily synced across different repos and apps.

In this post, we’ll see how using Bit you can easily create a simple HOC and share it across projects to be used, developed and synced where needed.

Pollable.js

A simple but frequent use case for a component is to execute some piece of code repeatedly over a fixed time interval.

In this post, we will design this functionality as a Higher Order Component that can be used to compose other components and inject this feature when needed. This example is simple as it is practical.

Pollable.js

Give a quick glance at the Higher Order Component that we have written above and we will get back to discuss the internal details. The simple way to use this in a child component would be to decorate the HOC at the time of defining the child component like this:

class Timer extends Component {

....

} export default Pollable(5)(Timer)

The Pollable component will have to be called twice, once with the timeIntervalInSeconds parameter and then the next invocation would be the actual child component (Timer in our example) that will make use of the polling functionality.

The rest of this blog post will comprise of two parts:

exporting Pollable.js HOC as a Bit component from an existing project

Using the Bit component to create a Bitcoin Price Ticker component

Exporting Pollable.js HOC as a Bit component

Most opportunities for creating a HOC arise in existing projects when you see a pattern where a functionality is being used in more than one place. That is when you can refactor the React component into a HOC and use it in other components as needed.

In this case, we find that the poller feature is cross-cutting and can be distributed as a reusable component. So, instead of working hard to remove it from the original sourcecode and publish a package, we can simply use Bit to isolate the HOC and use it where it’s needed with little to no overhead.

It will also enable us to make changes to the component right from different repos using it, while changes can be later synced between them as needed. Bit also provides isolated testing, build and even a live components playground.

Example React “Hero” component shared with Bit

Looking at our existing application’s project structure, Pollable.js is available as a util function reused within the project.

.

├── bit.json

├── package.json

└── src

├── complex-app

│ ├── actions

| ├── components

| ├── reducers

│ └── index.js

└── utils

├── Pollable.js

└── readme.md

First step would be to install the bit binary and initialise the workspace

$ npm install bit-bin -g

$ bit init

Then, add the files that will be part of the bit component

$ bit add src/utils/Pollable.js --id components/pollable

$ bit add src/utils/readme.md --id components/pollable

We add the files essential to make the Pollable.js component work in isolation which in this case is pretty much the single file itself. Good to add an optional readme.md file that serves as documentation for the component. If you have any, you can also specify test files to become part of the component, and Bit will run the tests in isolation and present the results in the CLI/Web UI.

Now, let’s tag the added files to lock a version for the component.

$ bit tag --all 0.0.1

Bit uses semantic versioning, so let’s start with 0.0.1 and increment with every release.

Sinc, Pollable.js is a react component, we must instruct Bit as to how this component will be built and packaged. There are list of compilers available depending on the project and we will use what is appropriate in our case and run the build, and you can also extend and implement your own.

$ bit import bit.envs/compilers/react -c

$ bit build

Now, we are all set. Assuming you have an account with bitsrc.io, click on the + CREATE SCOPE button to the top right corner and create a new scope for the component we are about to export. I am naming my scope as rcdexta.hoc and will use it in the next command:

$ bit export rcdexta.hoc

After bit-cli informs you that the export was successful, navigate to your account’s scope page and you should see something like this!

Using the Pollable.js Bit component to create a Bitcoin Price Ticker component

Let’s use the component that we exported previously in a brand new react application to build a realtime Bitcoin Price Ticker app.

We will use create-react-app generator to bootstrap a clean slate react application:

$ npx create-react-app bitcoin-ticker

If you have issues running the command, refer to create-react-app docs.

Once, the generator runs successfully, check if the app is running correctly:

$ cd bitcoin-ticker

$ yarn start

You should see the browser open on localhost:3000 and the Welcome to React message.

There are several ways to import the Bit component into a react application. The cool thing about Bit is it allows you to install the component as a npm package, or import the source code itself to modify and update it rght from any project using it. In this case, since we don’t need to change it, let’s install it with NPM.

To know the package name, refer to the section to the right on the component page, which looks like this:

Bit component as yarn package

Since create-react-app comes with yarn by default, we will use the steps to add it via yarn. Hover over the package name, to add the yarn config to let yarn know that it has check in bit’s package repository for packages with @bit prefix. The command should be very similar to this one:

$ yarn config set "@bit:registry" "https://node.bitsrc.io/"

Then, let’s make yarn add the package as a dependency to our application:

And the command should install the package and add it as a runtime dependency to package.json

Now, let’s go ahead and build our Bitcoin ticker. Create a new file called BitcoinTicker.js inside the src folder and add the following as seen in the snippet:

Couple of things to note:

You see that the last line helps include Pollable.js as the Higher Order Component that takes in 5 seconds as the time interval and our new component as the child component.

Pollable.js will inject onInterval as a prop to the child component that we are using in line 8

as a prop to the child component that we are using in line 8 The refresh function will be invoked by the HOC every 5 seconds which talks to a Bitcoin public api to fetch the real price periodically.

function will be invoked by the HOC every 5 seconds which talks to a Bitcoin public api to fetch the real price periodically. After every invocation of refresh method, the state is changed and the same is reflected in the render method

Now, modify App.js to use our ticker

import React, { Component } from 'react';

import logo from './logo.svg';

import './App.css';

import BitcoinTicker from './BitcoinTicker' class App extends Component {

render() {

return (

<div className="App">

<BitcoinTicker/>

</div>

);

}

} export default App;

And switch to the browser and you should see the screen below:

Realtime Bitcoin Ticker

The ticker will be refreshed every 5s and the time would be updated accordingly. That’s it!

Conclusion

In this post we’ve learned how to leverage React’s compositional nature along with Bit, in order to quickly extract reusbale code from our component into a High Order Component and use it wherever it’s needed.

You can learn more about React, Bit and Atomic design here. Hope you liked this post and feel free to comment, ask of suggest anything. Cheers.