DEV Community

Cover image for Implementing Higher Order Components (HOC) for Functional Components in ReactJS
Ashfiquzzaman Sajal
Ashfiquzzaman Sajal

Posted on

Implementing Higher Order Components (HOC) for Functional Components in ReactJS

In ReactJS, Higher Order Components (HOC) is a powerful pattern that allows us to reuse component logic across multiple components. While HOCs are commonly used with class components, they can also be implemented with functional components. In this article, we will explore how to create and use Higher Order Components with functional components.

What is a Higher Order Component (HOC)?
A Higher Order Component is a function that takes a component as an argument and returns a new component with enhanced functionality. It allows us to add additional props, modify the component's behavior, or encapsulate common logic that can be shared across multiple components.

Creating a Higher Order Component for a Functional Component:
To create a Higher Order Component for a functional component, we can follow these steps:

Step 1: Define the Higher Order Component function:

const withEnhancements = (WrappedComponent) => {
  const EnhancedComponent = (props) => {
    // Add your enhanced logic here
    // You can modify props or add additional functionality

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

  return EnhancedComponent;
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Use the Higher Order Component:
To use the Higher Order Component, wrap your functional component with the HOC function:

const MyFunctionalComponent = (props) => {
  // Your component's code here
};

const EnhancedFunctionalComponent = withEnhancements(MyFunctionalComponent);
Enter fullscreen mode Exit fullscreen mode

Step 3: Render the Enhanced Functional Component:
Finally, render the enhanced functional component in your application:

ReactDOM.render(
  <EnhancedFunctionalComponent />,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Example: Adding a Loading Indicator to a Functional Component
Let's consider an example where we want to add a loading indicator to a functional component. We can create a Higher Order Component that handles the loading state and displays the indicator accordingly:

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

    useEffect(() => {
      // Simulating an asynchronous operation
      setTimeout(() => {
        setLoading(false);
      }, 2000);
    }, []);

    return isLoading ? <div>Loading...</div> : <WrappedComponent {...props} />;
  };

  return EnhancedComponent;
};

const MyComponent = () => {
  // Your component's code here
};

const EnhancedComponentWithLoading = withLoadingIndicator(MyComponent);

ReactDOM.render(
  <EnhancedComponentWithLoading />,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

In the above example, the withLoadingIndicator HOC takes a functional component MyComponent as an argument and returns a new component EnhancedComponent. The EnhancedComponent handles the loading state, displays a loading indicator for 2 seconds, and then renders the original MyComponent.

Conclusion:
Higher Order Components are a powerful pattern in ReactJS that allows for component reusability and logic sharing. By implementing HOCs for functional components, we can enhance their functionality, modify behavior, or encapsulate common logic. Use this pattern wisely to create more flexible and maintainable ReactJS applications.

Follow me on X/Twitter

Top comments (5)

Collapse
 
brense profile image
Rense Bakker

HoCs are an anti-pattern though. Create a custom hook instead, if you have reusable logic that can be used by multiple components, or a wrapper component if you need to repeat certain UI elements (or a combination). HoCs were often used to set properties on child components in an obscure way, which is terrible for debugging. Hooks don't have this problem because they either manage their own internal state, or they have to explicitly return a value that can be handled outside of the hook.

Collapse
 
ashsajal profile image
Ashfiquzzaman Sajal

Thanks for your valuable comment Rense Bakker. Hooks and HoCs serve different purposes in React. Hooks are primarily used for managing component state and side effects within functional components, while HoCs are used for enhancing component behavior by wrapping them with additional functionality. while custom hooks are a great alternative for sharing logic, Higher Order Components are not inherently bad or an anti-pattern. They offer a different approach to code reuse and can be used effectively with proper design and consideration for readability and maintainability.

Collapse
 
brense profile image
Rense Bakker

No, custom hooks serve the same purpose of enhancing component behavior. HoCs are basically their predecessor from the React Class component era and the problems they caused are one of the major reasons why we have react hooks now.

Thread Thread
 
ashsajal profile image
Ashfiquzzaman Sajal

Indeed! Thank you for your information Rense Bakker.

Collapse
 
ashsajal profile image
Ashfiquzzaman Sajal

Are you confused with Higher Order Component (HOC) ?