Higher-Order Components

react-higher-order components

An advanced React technique for reusing component logic is called a higher-order components (HOC). HOCs aren’t technically a part of the React API; they are a pattern that React’s compositional structure produces.

A function that takes a component and returns another component is an example of a higher-order component.

const NewComponent = HOC(WrappedComponent);

HOCs essentially use the programming principle of “don’t repeat yourself” (DRY), which you’ve probably encountered at some point in your career as a software developer. It is one of the most well-known software development principles, and adhering to it is crucial when creating applications or developing code in general.

Higher-Order Functions In JavaScript:

Let’s briefly review higher-order functions in JavaScript before moving further on to HOCs in React. It is essential to comprehend them in order to comprehend our main subject.

In JavaScript, higher-order functions accept one function as an input and return another function. They allow us to abstract beyond only values and over activities, They come in a variety of formats, and when we use them to work with functions and even arrays, we end up writing less code.

Composition is the most intriguing aspect of using higher-order functions. Small functions that deal with a single logic component can be created. The various tiny functions we have constructed can then be combined to form complex functionalities. As a result, our code base has fewer defects and is
considerably simpler to read and comprehend.


JavaScript has some of these functions already built in. Some examples of higher-order functions are the following:

// Example #1
const filter = (predicate, xs) => xs.filter(predicate)
const is = type => x => Object(x) instanceof type
filter(is(Number), [0, '1', 2, null]) // [0, 2]

// Example #2
const withCounter = fn => {
  let counter = 0
  return (...args) => {
    console.log(`Counter is ${++counter}`)
    return fn(...args)
  }
}

const add = (x, y) => x + y
const countedSum = withCounter(add)
console.log(countedSum(2, 3))
console.log(countedSum(2, 1))

Here are some examples of real-world HOCs you might have come across:

  1. react-redux connect(mapStateToProps, mapDispatchToProps)(UserPage)
  2. material-ui withStyles(styles)(UserPage)
  3. react-router withRouter(UserPage)

Facts about Higher-Order Components

  • Components are not altered or mutated by us. We produce fresh ones.
  • Components are assembled using a HOC to enable code reuse.
  • A pure function is a HOC. It just produces a new component and has no side effects.

Structure Of A Higher-Order Component:

A higher-order function is similar in structure to a HOC:

  • It is a component.
  • It uses a different component as an argument.
  • Then, a new component is returned.
  • It can render the original component that was supplied to it using the component that it returns.

Create A Custom Higher-Order Component:

So, generate a new React app with create-react-app, like (getting started?)

npx create-react-app my-app

Replace the code in your index.js file with the following snippet once your app is created.

import React from 'react';
import { render } from 'react-dom';

const HelloWorld = ({ name }) =>
  <h1>
    Hello {name}!
  </h1>;

function withWorld(WrappedComponent) {
  return class extends React.Component {
    render() {
      return <WrappedComponent name="World" {...this.props} />;
    }
  };
}
const HelloWorldComponent = withWorld(Hello);
const App = () =>
    <HelloWorldComponent />
render(<App />, document.getElementById('root'));

Conclusion:

React Higher-Order Component is the implementation of functional programming ideas in your codebase at its most fundamental level. It is the function that returns a class. Since higher-order components often receive components as input and return other components as output, it is also feasible to send higher-order components to other higher-order components. However, this could result in your component tree having extraneous nesting.

Libraries such as Redux’s connect, react-router’s withRouter are good examples of why we should think about implementing higher-order components.

Higher-order components are generally used in React projects to reuse logic. They must, however, render some UI. HOCs are therefore problematic if you want to communicate some non-visual logic. React hooks appear to be the ideal solution in this situation.

45260cookie-checkHigher-Order Components

Leave a Reply