Frontend Development 10 min read

Understanding and Implementing Higher-Order Components in React

This article explains the concept of higher‑order components (HOCs) in React, demonstrates basic and advanced implementations—including parameterized HOCs, display‑name handling, composition with compose, and practical examples such as loading and copy utilities—while comparing HOCs with parent components and recommending open‑source libraries.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Understanding and Implementing Higher-Order Components in React

Before diving into higher‑order components (HOCs), the article revisits the definition of higher‑order functions: functions that take other functions as arguments or return a new function. An HOC is the React analogue, taking a component as input and returning an enhanced component.

The simplest HOC is shown, which wraps a given component with a header element. The implementation is provided as a function that returns a class extending Component and renders the header together with the wrapped component.

export default function withHeader(WrappedComponent) {
  return class HOC extends Component {
    render() {
      return (
我是标题
);
    }
  };
}

Usage with a decorator syntax is demonstrated, and the equivalent non‑decorator form is also shown.

@withHeader
export default class Demo extends Component {
  render() {
    return (
我是一个普通组件
);
  }
}

To keep the original component name visible in the React DevTools, the article adds a getDisplayName helper and a static displayName property to the HOC.

function getDisplayName(component) {
  return component.displayName || component.name || 'Component';
}
export default function (WrappedComponent) {
  return class HOC extends Component {
    static displayName = `HOC(${getDisplayName(WrappedComponent)})`;
    render() {
      return (
我是标题
);
    }
  };
}

The article then shows how to parameterize the header text, turning the HOC into a factory that accepts a title argument.

export default function (title) {
  return function (WrappedComponent) {
    return class HOC extends Component {
      render() {
        return (
{title ? title : '我是标题'}
);
      }
    };
  };
}

Composition of multiple HOCs is introduced using the compose utility, allowing developers to stack enhancements such as withHeader and withLoading in a clear functional style.

const enhance = compose(withHeader, withLoading);
@enhance
class Demo extends Component { /* ... */ }

Advanced patterns are discussed, including property‑proxy HOCs, reverse‑inheritance HOCs (which extend the wrapped component to access its state and lifecycle), and the use of curry to generate HOCs with different parameters.

A practical loading HOC is provided, which conditionally renders an Ant Design Spin component based on a user‑supplied check function.

export default function (loadingCheck) {
  return function (WrappedComponent) {
    return class extends WrappedComponent {
      render() {
        if (loadingCheck(this.props)) {
          return (
{super.render()}
);
        }
        return super.render();
      }
    };
  };
}

A copy‑to‑clipboard HOC is also presented, which adds copy functionality to any component without altering its internal rendering.

export default copy = (targetName) => (WrappedComponent) => {
  return class extends Component {
    componentDidMount() {
      const ctx = this;
      const dom = ReactDom.findDOMNode(ctx);
      const nodes = {
        trigger: dom,
        target: dom.querySelector(targetName)
      };
      gotem(nodes.trigger, nodes.target, {
        success: () => message.success('复制成功'),
        error: () => message.error('复制失败,请手动输入')
      });
    }
    render() {
      return
;
    }
  };
};

The article contrasts HOCs with parent components, emphasizing that HOCs keep business logic separate from UI, leading to cleaner, more reusable code.

Finally, open‑source libraries such as recompact and react‑sortable are recommended for further exploration of HOC patterns.

In summary, higher‑order components implement the Decorator pattern in React, allowing developers to abstract common logic, layer functionality like an onion, and improve code maintainability and decoupling.

frontendJavaScriptreactdecoratorcompositionHigher-Order Component
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.