DEV Community

Cover image for React Higher Order Component
Rakib Hasan
Rakib Hasan

Posted on

React Higher Order Component

Definition

If a component takes another component as an argument and returns completely new component is called a higher-order component. Higher-order components are mainly wrapper components.

Example details:

suppose 2 component named ClickCounter **and **HoverCounter shares the same kind of state in there component. We can separate states from both counter and put them in Higher-order component and wrap them with **ClickCounter **and **HoverCounter **to share their state.

ClickCounter.js

import React from 'react';
import withCounter from './withCounter';

function ClickCounter({ count, incrementCount }) {
        return (
          <div className="w-full flex justify-center ">
            <button
              onClick={incrementCount}
              type="button"
              className="px-6 py-2 bg-green-500 rounded-lg text-white"
            >
              Clicked
              {' '}
              {count}
              {' '}
              times
            </button>
          </div>
        );
}

export default withCounter(ClickCounter);
Enter fullscreen mode Exit fullscreen mode

HoverCounter.js

import React from 'react';
import withCounter from './withCounter';

function HoverCounter({ count, incrementCount }) {
        return (
          <div className="w-full flex justify-center mt-8">
            <h1
              onMouseOver={incrementCount}
              className="text-green-600 tex-2xl font-bold border-2 border-solid border-gray-600 p-2"
            >
              Hover
              {' '}
              {count}
              {' '}
              times
            </h1>
          </div>
        );
}

export default withCounter(HoverCounter);
Enter fullscreen mode Exit fullscreen mode

Higher Order Function: withCounter.js

import React, { Component } from 'react';

const withCounter = (OrginalComponent) => {
    class NewCounter extends Component {
        state = { count: 0 };

        incrementCount = () => {
            this.setState((prevState) => ({ count: prevState.count + 1 }));
        };

        render() {
            const { count } = this.state;
            return (
              <OrginalComponent count={count} incrementCount={this.incrementCount} />
            );
        }
    }
    return NewCounter;
};

export default withCounter;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)