Front end developer specialising in JavaScript and React. Experienced in all aspects of modern front end development. Passionate about making accessible, secure and performant software.
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.
constwithBlogPostData=(WrappedComponent)=>{constComponent=(props)=>{constblogPostData='foo';// stuff to get blog post datareturn<WrappedComponentblogPostData={blogPostData}{...props}/>;
};returnComponent;};// then somewhere elseconstDisplayBlogPost=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.
constBlogPostView1=props=>{constblogPostData=useBlogPostData();// this is a custom react hook// return JSX here};constBlogPostView2=props=>{constblogPostData=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.
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.
Another thing is that higher order components can be stacked. We could do
withFoo(withBar(withBlogPostData(BlogPostView1)));
and it would work just fine. ObviouslyBlogPostView1
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.
Obviously I'm simplifying the example by not including
useEffect
orcomponentDidMount
, but I hope the explanation still comes through.So in cases of error handling, am sure it can useful then. will try and implement it. Thank you.