DEV Community

Cover image for Why to Use HOCs in React
Mohammed Awad
Mohammed Awad

Posted on Edited on

Why to Use HOCs in React

Higher-Order Components in React (HOC)

Imagine you're a magician and you have a magic box. You can put anything into this box, say a rabbit, and the box will add a hat to it. Now, every time you pull out a rabbit, it's wearing a hat! This is what Higher-Order Components (HOCs) do in React. They're like the magic box that adds extra features or behaviors to a component.


What is a Higher-Order Component (HOC)?

In React, a Higher-Order Component (HOC) is a function that takes a component as an argument and returns a new component with added features or behaviors. It's a way of reusing component logic across multiple components without modifying their code. This makes them a flexible and reusable way to add functionality to your components.


When and How to Use HOCs?

In the real world, as a developer, you often find yourself writing code that is repetitive or similar in nature. This is where Higher-Order Components (HOCs) come to the rescue in React. I recently used a HOC in my project, an "Arab van"(rental system), and it greatly simplified my code by abstracting out common logic.

I had to fetch data in multiple components. Instead of repeating the fetching logic in each component, I created a Higher-Order Component (HOC) named withFetchData.

Every HOC name starts by with like withFetchData

This HOC takes a component (WrappedComponent) and a fetchData function as its arguments.

export default function withFetchData(WrappedComponent, fetchData) {
  return function (props) {
  const memoizedFetchData = useCallback(() => fetchData(id), [id]);
  const { value, loading, error, execute } = useAsync(
      memoizedFetchData,
      false
    );

    useEffect(() => {
      if (!loading) {
        execute();
      }
    }, [location]);

    return <WrappedComponent data={value} vanId={id} 
           {...props} />;
  };
}
Enter fullscreen mode Exit fullscreen mode

And here's how you can use it:

const EnhancedComponent = withFetchData(MyComponent, fetchData);
Enter fullscreen mode Exit fullscreen mode

The result is a new component (EnhancedComponent) that behaves exactly like MyComponent, but with added data fetching capabilities.


Why I Chose HOC

The reason I chose to use an HOC for this purpose was twofold:

Code Reusability: By encapsulating the data fetching logic inside a HOC, I was able to reuse this logic across multiple components, thereby reducing code duplication and making the codebase cleaner and more maintainable.
Separation of Concerns: The HOC allowed me to separate the data fetching logic from the presentation logic of my components. This made the components easier to understand, test, and maintain.


In conclusion,

Higher-order components are a powerful tool in React that allows you to write cleaner, more reusable code. I found them to be incredibly useful in my "rental van app" project, and I believe they can be beneficial in many other scenarios as well.

Remember, every line of code you write is a step towards becoming a better developer. Keep learning, keep growing, and most importantly, have fun along the way!


As a React developer, I'm currently on the lookout for new opportunities. If you know of any roles where my experience could be a good fit, I would love to hear from you.

You can reach out to me anytime at my email xMohammedAwad@gamil.com, or connect with me on LinkedIn. Check out my projects on GitHub to see more examples of my work.

Muhmmad Awd

Top comments (1)

Collapse
 
xmohammedawad profile image
Mohammed Awad •

what you think ?