Skip to main content

Command Palette

Search for a command to run...

What are Higher Order Components?

Updated
2 min read
What are Higher Order Components?

In React, higher-order components (HOCs) are functions that take a component as input and return an enhanced version of that component. They are a way to reuse component logic and share common functionality across multiple components.

In functional components, you can use higher-order components by utilizing the concept of "function composition." Here's an example of how you can create and use an HOC in a functional component:

import React, { useState, useEffect } from 'react';

const withLoading = (WrappedComponent) => {
  const EnhancedComponent = (props) => {
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
      // Simulating an API call delay
      const delay = setTimeout(() => {
        setIsLoading(false);
      }, 2000);

      return () => clearTimeout(delay);
    }, []);

    if (isLoading) {
      return <div>Loading...</div>;
    }

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

  return EnhancedComponent;
};

const DataComponent = ({ data }) => {
  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};

const EnhancedDataComponent = withLoading(DataComponent);

const App = () => {
  const data = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    { id: 3, name: 'Item 3' },
  ];

  return <EnhancedDataComponent data={data} />;
};

export default App;

In this example, the withLoading HOC adds a loading state (isLoading) to the wrapped component. When the component is rendered, it starts in a loading state and displays the "Loading..." message. After a simulated delay of 2 seconds, the loading state is set to false, and the wrapped component (DataComponent) is rendered with the provided data.

You can use the EnhancedDataComponent in your app, and it will automatically handle the loading state and display the loading spinner while the data is being fetched.

This is just one example of how you can use higher-order components in functional components to add reusable functionality. HOCs can be used for various purposes, such as handling authentication, data fetching, styling, and more. The key is to identify reusable logic that can be encapsulated within an HOC and applied to multiple components in your application.

More from this blog

R

Raja Muhammad Asher - Senior Software Engineer - Full Stack Developer

157 posts

Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, ExpressJS, MySQL, MongoDB. Love collaborating & making a difference