Skip to content

Understanding Higher-Order Components (HOC) in React

May 12, 2024

Higher-Order Component (HOC)

A Higher-Order Component is a function that takes a component and returns a new component with additional props or behavior. This pattern allows you to abstract and reuse logic across multiple components, enhancing code maintainability and reducing duplication.

Key Characteristics of HOCs

Why Use HOCs?

HOCs are useful for:

Implementing an HOC in TypeScript

Let’s implement an example HOC in TypeScript that adds a simple logging functionality to any component. This HOC will log the component’s props whenever it renders.

Step 1: Define the HOC

First, we’ll create the HOC function. This function will take a component and return a new component that logs props.

import React, { ComponentType, useEffect } from "react";

function withLogging<P>(WrappedComponent: ComponentType<P>): ComponentType<P> {
  return (props: P) => {
    useEffect(() => {
      console.log("Current props:", props);
    }, [props]);

    return <WrappedComponent {...props} />;
  };
}

export default withLogging;

Step 2: Create a Wrapped Component

Next, let’s create a simple component that we will wrap with our withLogging HOC.

import React from "react";

interface HelloWorldProps {
  name: string;
}

const HelloWorld: React.FC<HelloWorldProps> = ({ name }) => {
  return <div>Hello, {name}!</div>;
};

export default HelloWorld;

Step 3: Wrap the Component with HOC

Now, we’ll wrap the HelloWorld component with the withLogging HOC and render it.

import React from "react";
import ReactDOM from "react-dom";
import HelloWorld from "./HelloWorld";
import withLogging from "./withLogging";

const HelloWorldWithLogging = withLogging(HelloWorld);

ReactDOM.render(
  <HelloWorldWithLogging name="React Developer" />,
  document.getElementById("root")
);

Explanation

Conclusion

Higher-Order Components (HOCs) are a powerful pattern in React for enhancing components with additional functionality.

By abstracting common logic into HOCs, you can create more reusable and maintainable code.

In this example, we demonstrated how to implement an HOC in TypeScript to log props, but the possibilities with HOCs are vast, including handling authentication, theming, and more.