Download CV

How to use React higher-order component

December 19, 2022 / 1 min read

In React, a higher-order component (HOC) is a function that takes a component and returns a new component. HOCs are a way to reuse code, abstract away logic, or add additional functionality to a component.

Here is an example of how you might use a HOC in React:

import React from 'react';

// This is the HOC
function withLoadingIndicator(WrappedComponent) {
  return function WithLoadingIndicator(props) {
    if (props.isLoading) {
      return <p>Loading...</p>;
    } else {
      return <WrappedComponent {...props} />;
    }
  }
}

// This is the component that will be wrapped by the HOC
function MyComponent(props) {
  return <p>{props.text}</p>;
}

// This creates a new component that has the loading indicator functionality
const MyComponentWithLoadingIndicator = withLoadingIndicator(MyComponent);

// You can then use the new component like any other component
function App() {
  return (
    <div>
      <MyComponentWithLoadingIndicator text="Hello World" isLoading={false} />
    </div>
  );
}

In the example above, the HOC withLoadingIndicator takes a component WrappedComponent and returns a new component that displays a loading indicator when the isLoading prop is true, and displays the WrappedComponent when isLoading is false.

You can use HOCs to add functionality to a component without modifying the component itself, which can make it easier to reuse and maintain the component.