Understanding Higher-Order Components in ReactJS

 

@Author: damminhtien :whale:

@CreatedAt: 07/01/2020

@LastUpdate: 07/12/2020

1. Intro and definition

In office website of ReactJS introduce a pattern called High Order Component (HOC for short). 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 with additional functions. Then, you suddenly realise the concept of HOC is quite same as Decorator design pattern.

HOC

Higher order components, in general, are a functional programming methodology. If you are familiar with Redux, you surely use connect() function look like:

import {connect} from 'react-redux';
// code
export default connect(mapStateToProps, mapDispatchToProps)(ExampleComponent);

connect is a HOC. This post aims to describe what is HOC and how it works.

2. Advantages

While feeling you re writing professional code, you will be received many benefits from HOC:

  • Your code is maintainable and scalable: every single time you want to add new styles or properties to nested components, you can try to add them into HOC. In the near future, you change the properties, change one time in HOC. Furthermore, your code is also shorter.
  • Your old code doesn’t need to refactor: You don’t modify or mutate the old components. You create new ones wrap them.

[Disclaimer :boom:] If you are new with React or Javascript, you shouldn’t try HOC in the very first time. I suggest you to practice coding normal classes, and when you find the same, you will recognise when you should try this.

3. Example

Let’s making your hand dirty by trying some code.

A HOC takes a component as input parameter and returns a new component. Let’s look at an example of the most simple HOC possible.

// Take in a component as argument WrappedComponent
function simpleHOC(WrappedComponent) {
  // And return a new anonymous component
  return class extends React.Component{
    render() {
      return <WrappedComponent {...this.props}/>;
    }
  }
}

References:

  1. Higher-Order Components (@ReactJS.org): https://reactjs.org/docs/higher-order-components.html