DEV Community

Albert
Albert

Posted on

High Order Components (React)

When will be it be useful to use a high order components in react?

Top comments (4)

Collapse
 
sargalias profile image
Spyros Argalias

They're useful for reusing logic.

For the sake of example, imagine that we have two different views for blog posts, but we get their data in the same way.

Instead of duplicating the logic for both views, we could have the logic in a higher order component and pass in whichever of the two views we wanted.

const withBlogPostData = (WrappedComponent) => {
  const Component = (props) => {
    const blogPostData = 'foo'; // stuff to get blog post data
    return <WrappedComponent blogPostData={blogPostData} {...props} />;
  };
  return Component;
};

// then somewhere else
const DisplayBlogPost = withBlogPostData(BlogPostView1); // or withBlogPostData(BlogPostView2)
return <DisplayBlogPost />;

Another thing is that higher order components can be stacked. We could do withFoo(withBar(withBlogPostData(BlogPostView1))); and it would work just fine. Obviously BlogPostView1 would need to be coded correctly to use all the props it would receive.

However these days we tend to use React custom hooks instead.

const BlogPostView1 = props => {
    const blogPostData = useBlogPostData(); // this is a custom react hook
    // return JSX here
};
const BlogPostView2 = props => {
    const blogPostData = useBlogPostData(); // this is a custom react hook
    // return JSX here
};

Obviously I'm simplifying the example by not including useEffect or componentDidMount, but I hope the explanation still comes through.

Collapse
 
albertdugba profile image
Albert

So in cases of error handling, am sure it can useful then. will try and implement it. Thank you.

Collapse
 
kildareflare profile image
Rich Field

I've just finished reading this post which describes HOC and some alternative approaches to reusing components.

Collapse
 
albertdugba profile image
Albert

Thank you. will check it out