17 Feb 2024




Advanced

Higher-Order Components (HOC) in React are functions that accept a component and return a new component with enhanced functionality.

Higher-Order Component (HOC) in React typically looks like this:

jsx Syntax:

const EnhancedComponent = higherOrderComponentFunction(WrappedComponent);

tsx Syntax:

const EnhancedComponent: React.ComponentType<Props> = higherOrderComponentFunction(WrappedComponent);

In the above HOC syntax:

  • higherOrderComponentFunction is the Higher-Order Component (HOC) function. It's a function that takes a component (in this case, WrappedComponent) as an argument and returns an enhanced version of that component.
  • WrappedComponent is a React component that is being passed as an argument to the higherFunction. This component will be enhanced by the higherFunction to create a new component, which is assigned to newComponent.
  • EnhancedComponent refers to the component returned by the Higher-Order Component higherOrderComponent. This component is the enhanced version of the WrappedComponent, which means it may have additional props, behavior, or functionality provided by the HOC.

Example:

In TypeScript with JSX (.tsx), the syntax for using Higher-Order Components (HOC) remains the same as in JavaScript with JSX. Here's how you can use HOC in a .tsx file:

  1. higherOrderComponent.tsx
import React from 'react';

// Define a Higher-Order Component (HOC) function
const higherOrderComponent = (WrappedComponent: React.ComponentType<any>) => {
    // Enhance the WrappedComponent here
    const EnhancedComponent = (props: any) => {
        // Enhance props or add additional functionality
        return <WrappedComponent {...props} />;
    };

    return EnhancedComponent;
};

export default higherOrderComponent;
  1. MyComponent.tsx
import React from 'react';

// Define a regular React component
const MyComponent = (props: any) => {
    return <div>{props.message}</div>;
};

export default MyComponent;
  1. App.tsx
import React from 'react';
import higherOrderComponent from './higherOrderComponent';
import MyComponent from './MyComponent';

// Use the HOC to enhance the component
const EnhancedMyComponent = higherOrderComponent(MyComponent);

// Usage of the enhanced component
const App = () => {
    return (
        <div>
            <EnhancedMyComponent message="Hello, HOC!" />
        </div>
    );
};

export default App;

In the above example:

  • WrappedComponent is of type React.ComponentType<any>, which means it can accept any React component as an argument.
  • MyComponent is a regular React component.
  • EnhancedMyComponent is the result of applying the HOC (higherOrderComponent) to MyComponent.
  • App is a component that renders the enhanced component (EnhancedMyComponent).

👉Examples of Higher-Order Component (HOC) in React js

reactjs
higher-order-component
hoc