{"id":159786,"date":"2021-01-21T17:00:30","date_gmt":"2021-01-21T14:00:30","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it\/"},"modified":"2021-01-21T17:00:30","modified_gmt":"2021-01-21T14:00:30","slug":"how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it\/","title":{"rendered":"#How to Use Higher Order Components to Reuse Logic in React \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a3b726301d63\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a3b726301d63\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it\/#A_Simple_Example\" >A Simple Example<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it\/#Introducing_the_HOC\" >Introducing the HOC<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it\/#Using_the_HOC\" >Using the HOC<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-higher-order-components-to-reuse-logic-in-react-cloudsavvy-it\/#Advantages_of_HOCs\" >Advantages of HOCs<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#How to Use Higher Order Components to Reuse Logic in React \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-8770\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/320fa525975dcd73d87d71de862f3009\/p\/uploads\/2021\/01\/24b43beb.jpg\" alt=\"React logo on a dark background\" width=\"1602\" height=\"902\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Higher Order Components (HOCs) are a kind of React component which help you to reuse logic across your <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">app<\/a>lication. The terminology may sound complex but HOCs are easy to get grips with and can make your codebase simpler to maintain.<\/p>\n<p>A <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/reactjs.org\/docs\/higher-order-components.html\">Higher Order Component<\/a> always wraps child components with additional functionality. A HOC is defined as a function which accepts a component as a parameter. It then returns a <em>new<\/em> component, which will typically render the input component wrapped with extra props.<\/p>\n<h2 id=\"a-simple-example\"><span class=\"ez-toc-section\" id=\"A_Simple_Example\"><\/span>A Simple Example<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The best way to appreciate when HOCs make sense is to see them in action. Let\u2019s consider a simple checkout system where the state of the user\u2019s basket is stored centrally within the application. Our examples show Redux as the state store but this for illustrative purposes only.<\/p>\n<p>Assume this object represents our app\u2019s state:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"json\">\n<pre class=\"de1\">{&#13;\n    checkout: {&#13;\n        items: [&#13;\n            {&#13;\n                label: \"Product 1\",&#13;\n                price: 150.00,&#13;\n                quantity: 2&#13;\n            },&#13;\n            {&#13;\n                label: \"Product 2\",&#13;\n                price: 75.00,&#13;\n                quantity: 1&#13;\n            }&#13;\n        ]&#13;\n    }&#13;\n}<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>We have a simple array which represents the items in the user\u2019s basket. Our checkout components are going to derive additional values from this state, such as the total order value and the taxes to apply.<\/p>\n<p>Our checkout system will probably need to show the total value within multiple independent components. There might be a sidebar widget showing the basket, a post-checkout review screen and a shipping cost calculator. A naive system that simply passed the checkout items as props would risk duplication of logic \u2013 each component would need to work out the total order value for itself.<\/p>\n<h2 id=\"introducing-the-hoc\"><span class=\"ez-toc-section\" id=\"Introducing_the_HOC\"><\/span>Introducing the HOC<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let\u2019s look at how a HOC can help:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw5\">import<\/span> React from <span class=\"st0\">\"react\"<\/span><span class=\"sy0\">;<\/span>\n<span class=\"kw5\">import<\/span> <span class=\"br0\">{<\/span>connect<span class=\"br0\">}<\/span> from <span class=\"st0\">\"react-redux\"<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> withCheckout <span class=\"sy0\">=<\/span> ComponentToWrap <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n    <span class=\"kw1\">const<\/span> ComponentWithCheckout <span class=\"sy0\">=<\/span> <span class=\"kw5\">class<\/span> <span class=\"kw5\">extends<\/span> React.<span class=\"me1\">Component<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n        render<span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"br0\">{<\/span>\n            <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n                <span class=\"sy0\">&lt;<\/span>ComponentToWrap\n                    checkoutItems<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span><span class=\"kw1\">this<\/span>.<span class=\"me1\">props<\/span>.<span class=\"me1\">checkout<\/span>.<span class=\"me1\">items<\/span><span class=\"br0\">}<\/span>\n                    checkoutTotal<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span><span class=\"kw1\">this<\/span>.<span class=\"me1\">total<\/span><span class=\"br0\">}<\/span>\n                    <span class=\"br0\">{<\/span>...<span class=\"kw1\">this<\/span>.<span class=\"me1\">props<\/span><span class=\"br0\">}<\/span> <span class=\"sy0\">\/&gt;<\/span>\n            <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n        <span class=\"br0\">}<\/span>\n\u00a0\n        <span class=\"kw1\">get<\/span> total<span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"br0\">{<\/span>\n            <span class=\"kw1\">const<\/span> prices <span class=\"sy0\">=<\/span> <span class=\"kw1\">this<\/span>.<span class=\"me1\">props<\/span>.<span class=\"me1\">checkout<\/span>.<span class=\"me1\">items<\/span>.<span class=\"me1\">map<\/span><span class=\"br0\">(<\/span>i <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">(<\/span>i.<span class=\"me1\">quantity<\/span> <span class=\"sy0\">*<\/span> i.<span class=\"me1\">price<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n            <span class=\"kw1\">return<\/span> prices.<span class=\"me1\">reduce<\/span><span class=\"br0\">(<\/span><span class=\"br0\">(<\/span>a<span class=\"sy0\">,<\/span> b<span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">(<\/span>a <span class=\"sy0\">+<\/span> b<span class=\"br0\">)<\/span><span class=\"sy0\">,<\/span> <span class=\"nu0\">0<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n        <span class=\"br0\">}<\/span>\n\u00a0\n    <span class=\"br0\">}<\/span>\n\u00a0\n    <span class=\"kw1\">return<\/span> connect<span class=\"br0\">(<\/span><span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>checkout<span class=\"br0\">}<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>checkout<span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"br0\">(<\/span>ComponentWithCheckout<span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"kw5\">export<\/span> <span class=\"kw1\">default<\/span> withCheckout<span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>The file exports a single function, <code>withCheckout<\/code>, that takes a React component as its only parameter (<code>ComponentToWrap<\/code>). Within the function, we create a new anonymous class that is itself a React component.<\/p>\n<p>This new component\u2019s <code>render<\/code> method creates an instance of the <code>ComponentToWrap<\/code> we passed into the function. We now have the opportunity to define the instance\u2019s props. We forward the checkout items array as <code>checkoutItems<\/code> and make the pre-computed total value available as <code>checkoutTotal<\/code>.<\/p>\n<p>Any props passed to the HOC are forwarded to the inner component, ensuring that it receives all the data it requires. The function returns the newly created anonymous class which is ready to be rendered throughout your application.<\/p>\n<p>We use the <code>connect<\/code> method of <code>react-redux<\/code> so the <code>checkout<\/code> prop within the HOC receives the value of the <code>checkout<\/code> key in our Redux store\u2019s state. This is an implementation detail \u2013 your HOC might maintain its own state or reach out to some other service within your application.<\/p>\n<h2 id=\"using-the-hoc\"><span class=\"ez-toc-section\" id=\"Using_the_HOC\"><\/span>Using the HOC<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Now it\u2019s time to put our HOC to use.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw5\">import<\/span> React from <span class=\"st0\">\"react\"<\/span><span class=\"sy0\">;<\/span>\n<span class=\"kw5\">import<\/span> withCheckout from <span class=\"st0\">\".\/withCheckout.js\"<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw5\">class<\/span> CheckoutReviewScreen <span class=\"kw5\">extends<\/span> React.<span class=\"me1\">Component<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n    render<span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"br0\">{<\/span>\n        <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n            <span class=\"sy0\">&lt;<\/span>h1<span class=\"sy0\">&gt;<\/span>Checkout<span class=\"sy0\">&lt;\/<\/span>h1<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>h2<span class=\"sy0\">&gt;<\/span><span class=\"br0\">{<\/span><span class=\"kw1\">this<\/span>.<span class=\"me1\">props<\/span>.<span class=\"me1\">checkoutTotal<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&lt;\/<\/span>h2<span class=\"sy0\">&gt;<\/span>\n        <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n    <span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"kw5\">export<\/span> <span class=\"kw1\">default<\/span> withCheckout<span class=\"br0\">(<\/span>CheckoutReviewScreen<span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>We assume our <code>withCheckout<\/code> HOC is saved to <code>withCheckout.js<\/code> in the same directory as our new checkout review screen component. By wrapping the component with our <code>withCheckout<\/code> HOC, we can access and display the total order value. We don\u2019t need to compute it ourselves or store it within the app\u2019s state. If we ever wanted to update how the total is calculated (such as to add a fixed handling charge), we only need to make the change in one place \u2013 within our HOC.<\/p>\n<p>You can now render <code>&lt;CheckoutReviewScreen \/&gt;<\/code> anywhere in your app. Our wrapped example doesn\u2019t need to be passed any props as it sources its data from our Redux store. Because it\u2019s wrapped with <code>withCheckout<\/code>, itself wrapped with Redux\u2019s <code>connect<\/code>, the review screen automatically receives a <code>checkoutTotal<\/code> prop which sums the prices of all the items in the app\u2019s state.<\/p>\n<p>It\u2019s now worth mentioning how we named our HOC: <code>withCheckout<\/code>. By convention, HOC names normally have a <code>with<\/code> prefix because they add something to the components they wrap. In our case, the HOC provides convenient access to our checkout basket which we\u2019d otherwise need to implement within each component.<\/p>\n<h2 id=\"advantages-of-hocs\"><span class=\"ez-toc-section\" id=\"Advantages_of_HOCs\"><\/span>Advantages of HOCs<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Using a HOC lets you abstract common behaviours out of components, minimising code duplication and increasing maintainability. HOCs enable a form of dependency injection. They help you keep your components simpler by allowing more to be passed in from the outside world.<\/p>\n<p>HOCs are common within the React ecosystem. In fact, we\u2019ve seen one within this article \u2013 <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/react-redux.js.org\/api\/connect\"><code>connect()<\/code>, part of <code>react-redux<\/code><\/a>, which subscribes your components to Redux state changes.<\/p>\n<p>HOCs are popular because they provide a method of code reuse that doesn\u2019t break the self-containment of components. The pattern utilises React\u2019s composability to let you attach extra functionality without the risk of side-effects.<\/p>\n<p>You could pass any component in your app to <code>withCheckout<\/code> without breaking anything \u2013 the HOC just attaches a few extra props. This is why it\u2019s so important your HOCs forward <em>all<\/em> the props they receive (<code>{...this.props}<\/code> in our example). They mustn\u2019t do anything that could interfere with the wrapped component\u2019s normal operation.<\/p>\n<p>It may feel like your components now have a dependency on your HOC. This isn\u2019t the case. You could export a second version of your component that isn\u2019t wrapped, giving consumers the choice of which they use.<\/p>\n<p>Your component actually only insists on receiving certain props \u2013 <code>checkoutTotal<\/code> in our case. This could be supplied by the HOC or by passing a value wherever the component is rendered. Our HOC makes development simpler but hasn\u2019t fundamentally changed the nature of our rendered components.\n<\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/9056\/how-to-use-higher-order-components-to-reuse-logic-in-react\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#How to Use Higher Order Components to Reuse Logic in React \u2013 CloudSavvy IT&#8221; Higher Order Components (HOCs) are a kind of React component which help you to reuse logic across your application. The terminology may sound complex but HOCs are easy to get grips with and can make your codebase simpler to maintain. A&#8230;<\/p>\n","protected":false},"author":1,"featured_media":159787,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/01\/24b43beb.jpg","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-159786","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/159786","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=159786"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/159786\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/159787"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=159786"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=159786"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=159786"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}