Higher Order Components in React

Rachna Ralhan
Rachna's Blog
Published in
2 min readJul 9, 2018

Higher order components in React is a basic component that is specifically made to reuse code inside our Application. A perfect use case would be when you end up duplicating code in your Application. This would be perfect situation to make a higher order component.

You can add functionality by adding a higher order component to your regular component.

A very simple example of a higher order component is the connect function from the react-redux library.

You will follow a sequence of steps to create a higher order component.

So you write the logic that you want to put in the reusable component. Then you will create a *.js file in your components folder. By convention, this files should start with lowercase and should follow the camelcase rule.

The boiler plate should look like this:

import React, { Component } from ‘react’;

export default (ChildComponent) => {

class ComposedComponent extends component {

render() {

return <ChildComponent />

}

return ComposedComponent;

}

Once you have your boilerplate written down, next add all your reusable code to it. Let’s imagine you have a function call navigateAway() that is reusable. Your final code will look like this:

import React, { Component } from ‘react’;

export default (ChildComponent) => {

class ComposedComponent extends component {

navigateAway() {

whatever logic you have here…

}

render() {

return <ChildComponent />

}

return ComposedComponent;

}

The last step is to pass down the props to your child component. The reason we have to do that is because, we are not adding a higher order component that received the props from the parent component. For the child component to receive these props, you have pass them down.

So you will have to do this:

return <ChildComponent {…this.props} />

That should be it, to create a Higher Order Component.

--

--