<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anil Chaudhary on Medium]]></title>
        <description><![CDATA[Stories by Anil Chaudhary on Medium]]></description>
        <link>https://medium.com/@simbathesailor007?source=rss-b461f75fa84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rpUGXISkCqqt8Ylkb4DdMw.jpeg</url>
            <title>Stories by Anil Chaudhary on Medium</title>
            <link>https://medium.com/@simbathesailor007?source=rss-b461f75fa84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:15:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simbathesailor007/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design Systems a boon or a heavy baggage]]></title>
            <link>https://simbathesailor007.medium.com/design-systems-a-boon-or-a-heavy-baggage-7e38b1950531?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e38b1950531</guid>
            <category><![CDATA[component-libraries]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 08:59:42 GMT</pubDate>
            <atom:updated>2021-07-09T15:40:48.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n7tSvwGQdbqyfLxr" /><figcaption>Photo by <a href="https://unsplash.com/@balazsketyi?utm_source=medium&amp;utm_medium=referral">Balázs Kétyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I like Design Systems. The idea itself is so great to think about. Once your design system is ready, your whole organization starts delivering consistent UI interfaces. Fewer bugs and fewer efforts.</p><blockquote><strong>But I wanted to ask, Is it always the case ?</strong></blockquote><h4><strong>Startups can’t afford it</strong></h4><p>Creating and Maintaining Design Systems is a full-time job.</p><p>It is definitely not for startups. They generally don’t have the resources and bandwidth to work on a design system.</p><p>Most of the time, the benefits of design systems look far-fetched, mostly not align with any startup&#39;s immediate goals. This is big.</p><h4><strong>Tooling Around Design Systems</strong></h4><p>The tooling around design systems is broken.</p><p>There are so many ways you can create your design systems</p><p>based on CSS variables, javascript objects e.t.c You can do it by a CSS-in-js solution, tailwind approach, or by just simple CSS variables.</p><p>Editors have integration with a few of them so that they can suggest you the</p><p>tokens. But then that is not at all helpful for someone who has a different flow of working</p><p>**<strong>e.g</strong>** I copy the CSS from Figma and then paste into the browser dev tools. Try everything in devtool. Once I am satisfied, I copy-paste it into my code. This feels natural to me.</p><p>Some people just type out the CSS in code and just see the visual on a separate screen. This approach sometimes feels like a lot of work when you are having only one screen</p><h4><strong>Just Remember a lot</strong></h4><p>Design tokens are just another thing to remember. People might say, why do you have to remember when it is suggested by the editor. Again don&#39;t tell me that also doesn&#39;t require some remember when choosing from options</p><p>Those extra design tokens that you have to remember don&#39;t translate well when you shift to some other design system or to a system having no system at all. I fear someday people will ask tailwind class names in the interview.</p><p>We all know plain CSS which can work across frameworks because the browser is constant.</p><p>A shout out to <strong><em>styled components</em> </strong>here. The creators of it have just done a perfect job of making sure that you just copy and paste basic CSS and it just works. That’s such a small thing, but very impactful.</p><p>You know CSS, you know <strong><em>styled-components.</em></strong></p><p>Even when you are looking at the elements tabs when working with styled-components. You get clear information of what an HTML element is referring to. Thanks to <strong><em>styled-components</em></strong> babel plugin.</p><p>I drifted a little towards styled-components, but it are just perfect for most of the cases. Obviously, styled-components have other benefits which are pretty common. But let’s not drift away further. Let’s go back to design systems.</p><p>Today just writing a valid CSS in the browser is not the end of the job. You added new styles in devtool. Now you have to write the corresponding design system code in the editor, which will look entirely different.</p><p>You see such a waste of CSS skills that actually could have been transferable.</p><h4><strong>Long discussions pulling out every ounce of energy</strong></h4><p>The unnecessary long discussions that happen for design token naming. Oh my god. That can take an eternity to end. You see here why startups cannot afford to have their own design system.</p><p>These discussions leave a bad taste for one or another most of the time.</p><h4><strong>UX and UI Bridge</strong></h4><p>Now, let’s talk about UX and UI bridge. How many companies do you really think to have a team where UX and UI teams have agreed on common conventions.</p><p>If you are lucky in terms of team, understanding, plus you have lots of time to make everyone happy, then that can be done. Again you see why startups cannot afford to have their own design system.</p><p>Dark and Light mode options are such a necessity for their obvious benefits(https://web.dev/prefers-color-scheme/). Now working from home during this pandemic. We sometimes work in the late evenings.</p><p>How about watching a white screen at night? Does it please your eyes?</p><p>Of course not.</p><p>If creating a design system would have been an easy thing. We would have seen a lot more websites having both modes.</p><p>Some people might say, you don’t require a design system for having dark mode and light mode. Yes, you don&#39;t need it at times. But if in a bigger app, the styles are controlled by the design system. It becomes very easy for you to roll out any mode.</p><p>I wish we could have great tooling and ecosystem around this design system.</p><blockquote>That’s all the major items, which I feel are broken in and around design systems.</blockquote><h4><strong>What do I expect from a design system?</strong></h4><p>1. Quick to roll out with standard naming conventions. Should be available to</p><p>every company irrespective of their size.</p><p>2. Ways to extend it if needed</p><p>3. Tools to work both ways, either the code first or browser devtool first. You should be able to copy something and paste it directly into your code. That way there is no extra repetitive thinking required.</p><p>4. Should not be very tightly coupled with UX work. They should be able to roll out designs and once you find certain inconsistencies e.g font size is 15px instead of multiple of 2. You can very well make it 16px or 14px.</p><p>If there any common components which designer might have introduced new behavior or dimensions. Most of the time design team is ok when you tell them we have this component already and this is the design that is slightly different than what you have provided.</p><p>5. No long discussions. UX and UI Teams should be able to move independently.</p><p>In the conclusion, I would say we have come a long way with the design systems, but lots of major problems are still unsolved.</p><h4><strong>Is it a boon or baggage?</strong></h4><p>I would say for most it’s baggage.</p><p>They can just use one open-source framework. This all does not help with all the problems e.g like dev experience is still pretty bad.</p><p>I wish the design systems could be a small investment and a good gains stuff.</p><p>But boy not now.</p><p>I can see lots of ongoing development happening around these problems in the community. The frontend community keeps on tackling bigger and difficult problems. I hope that it will be solved soon.</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e38b1950531" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle 404 pages for nested routes in react-router]]></title>
            <link>https://levelup.gitconnected.com/handle-404-pages-for-nested-routes-in-react-router-2b31572a5b2f?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b31572a5b2f</guid>
            <category><![CDATA[404-not-found]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 10:34:45 GMT</pubDate>
            <atom:updated>2021-03-10T13:38:39.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mE038tUxsvyLiDBz" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React router is one of the most used router in the React community.</p><p>It allows us to write `Routes` in nested forms. Routes are nothing but React components. Nested Routes have advantages when we want to show sub parts of pages based on conditions. Nested routes also cause less remounts as only the content for the nested route will mount again.</p><p><strong>Bit of why we need nested routes</strong></p><p>Let’s say we have a route system like this:</p><pre>&lt;Router&gt;</pre><pre>&lt;Route path=&quot;/checkout/passengerdetails&quot;&gt;&lt;ComponentA /&gt;&lt;/Route&gt;</pre><pre>&lt;Route path=&quot;/checkout/baggage&quot;&gt;&lt;ComponentB /&gt;&lt;/Route&gt;</pre><pre>&lt;/Router&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*dfDImcOgqDLUx1CU4CBZSA.png" /></figure><p>Now if we don’t have nested routes, the whole `ComponentA` will unmount and `ComponentB` will mount.</p><h3>Is that good ?</h3><p>Well, it’s how much love you have for performance over ease of writing. I would definitely say this way of writing routes is easy and straight forward.</p><p>But what problems exists with this routing ?</p><p>In the above diagram I have given color to the components, notice the common colored boxes between both the routes. Only the center component has changed between both the routes.</p><p>The route change from `/checkout/passengerdetails` to `/checkout/baggage` cause a complete unmount of all the components , even for the components which need not change with the route.</p><p>This is the exact situation where nested routes can be a great boon.</p><p>we can prevent the unmount of entire page by writing routes like this:</p><pre>function SomeComponent() {<br>  return (<br>    &lt;&gt;<br>      &lt;CommonUI /&gt;<br>      &lt;Switch&gt;<br>        &lt;Route path=&quot;passengerdetails&quot;&gt;<br>          &lt;PassengerDetails /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;baggage&quot;&gt;<br>          &lt;Baggage /&gt;<br>        &lt;/Route&gt;<br>      &lt;/Switch&gt;<br>      &lt;Footer /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>function App() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;Route path=&quot;/checkout&quot;&gt;<br>        &lt;SomeComponent /&gt;<br>      &lt;/Route&gt;<br>    &lt;/Router&gt;<br>  );<br>}</pre><p>In the example above notice , how `CommonUI` and `Footer` will not unmount when the route change happens.</p><p>That’s short gist of what can be achieved from nested routes.</p><h3><strong>Challenges with Nested Routes</strong></h3><p>One of the major challenge with nested routes is to handle `Not found` pages. Now as the routes are nested , there is no one place to keep the `Not Found` route. You have to place the not found route at the very end of nested routes.</p><p>See the diagram below to understand more.</p><p>Let’s say we have following route structure currently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEUuy58uaADdE48blG8yTQ.png" /></figure><p>Now let’s suppose we hit urls which looks something like these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*TpNJTJfa9EqdNlplLKs8gA.png" /></figure><p>How would you handle these routes to show 404 custom screen as none of routes matched ?</p><p>You can add `NotFound` component the end of every branch in tree diagram. Below is the diagram showcasing that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-12BrxQsEp_H6yBwHFHsw.png" /></figure><p>This solution will work but it is not the best possible due to one of the major drawback which is :</p><p>Any new branch of route you introduce, you will have to add `Not found` component at the very end always. So more surface area, there will be more chances of mistakes.</p><blockquote><strong>What can we do to fix this issue ? . Our goals are following:</strong></blockquote><p>1. A centralized way of handling the 404 pages.</p><p>2. There should be no need to manually add `Not Found` Routes.</p><h4><strong>Solution</strong></h4><p>We can do it if we can write a custom `Custom Switch` component, which add a `Not found` route automatically at the end of the every route branch. So instead of `Switch` component from react-router-dom we will be using `CustomSwitch` everywhere</p><p>That simple component will look something like this:</p><pre>import { Switch, useRouteMatch } from &quot;react-router-dom&quot;;</pre><pre>function NotFoundPage({ CustomNotFoundPage }) {<br>  const history = useHistory();<br>  useEffect(() =&gt; {<br>    history.push(&quot;/notfoundpage&quot;);<br>  }, []);<br>  return null;<br>}</pre><pre>function CustomSwitch(props) {<br>  const { children } = props;<br>  return (<br>    &lt;Switch&gt;<br>      {children}<br>      &lt;NotFoundPage /&gt;<br>    &lt;/Switch&gt;<br>  );<br>}</pre><p>And a `Not found` route at the top of all the routes in our application. Preferably where you are rendering your base route.</p><p>You can also make use of `useRouteMatch` in the component to check whether a `Not found` is rendered.</p><h4><strong>To summarize :</strong></h4><p>CustomSwitch will add the `Notfound` route at the end of very `Switch` block. No need to add NotFound routes manually. Whenever a Not found component is rendered, it will redirect to `/notfoundpage` due to logic that we have written in NotFound Component</p><p>Here is the codesandbox link for the example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fo3gtp&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fo3gtp&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fo3gtp%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fbe58eab4bf6fffa371ddb8610c470b/href">https://medium.com/media/7fbe58eab4bf6fffa371ddb8610c470b/href</a></iframe><p>What if we have two `CustomSwitch` component at the same level. Then the first `CustomSwitch` may throw off you to `notfound` page. But this scenario , I haven’t ever faced while working on application. Just point it out here for the sake of clarity and unseeable gotchas.</p><p>That’s all for now. There are one corner case with the solution which i can think when i am writing the article.</p><p>Thanks and let me know in comments what you liked and what you didn’t like.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b31572a5b2f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/handle-404-pages-for-nested-routes-in-react-router-2b31572a5b2f">Handle 404 pages for nested routes in react-router</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Pdf Preview Nightmare]]></title>
            <link>https://medium.com/swlh/solving-pdf-preview-nightmare-3f2a47f2b733?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2a47f2b733</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pdf-reader]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 10:38:00 GMT</pubDate>
            <atom:updated>2021-02-13T21:49:07.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nscQUYsX5xUwAiTC" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Do you ever has the need to preview `pdf` on web ?. It’s so common but still draws every ounce of energy from a developer to make it work properly on every device.</p><blockquote>Why it has to be so hard ?</blockquote><h4><strong>My Attempts</strong></h4><p>1. Just open the pdf in the new tab and the browser will take care of it to preview correctly.</p><p><strong>**Problem**</strong>: It’s not always the best experience for the user. You don’t want user to switch the context by moving to a separate tab. It looks much bad when it happens on mobile device. The better experience would be on the same page without sacrificing context.</p><p>2. Try to open the document in a iframe. The iframe can be bit tricky across browsers. There can be security restrictions and disallow policy for certain pdfs. E.g When I tried opening some sample pdf which were opening fine on desktop device were not rendering at all on mobile device.</p><p>This situation can be very difficult. You can’t do much there to make it work.</p><p>Can we not have something straightforward where I just provide <em>`pdf URL</em>` and it takes care of rest. Renders properly on every device and most of the browsers.</p><p>With the above goal I started my search for the best possible library on internet.</p><p>Nothing sort of helped until I found <a href="https://mozilla.github.io/pdf.js/">Mozilla pdf.js</a></p><p>It makes use of <a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream">Readable streams</a></p><p>After few hours of digging and reading through source I was like :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12CcmGavTHjSOk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12CcmGavTHjSOk%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZDk4dnZudXNtZ3U1ZGVseTdzNjV4bGM0cmE2M3VmcHF3aWNheHNwdiZlcD12MV9naWZzX2dpZklkJmN0PWc%2F12CcmGavTHjSOk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/c92149818d9ef22b010e5c150ededf3c/href">https://medium.com/media/c92149818d9ef22b010e5c150ededf3c/href</a></iframe><blockquote>But then was it ready for my Reactjs APP ?</blockquote><p>Nopes. Not at all.</p><p>Hence I have to write my own port of mozilla pdf.js for reactjs using examples from <a href="https://github.com/mozilla/pdf.js/blob/master/examples">https://github.com/mozilla/pdf.js/blob/master/examples</a></p><h4><strong>Pdf Preview implementation</strong></h4><p>I wanted a pdf mobile previewer and it seemed that mozilla pdf.js has example folder available.</p><p>I just needed to `<strong><em>Reactify</em></strong>` it.</p><p>First step is to add certain script to your html.</p><p>Add following scripts in your body tag.</p><pre>&lt;script src=”https://cdn.jsdelivr.net/npm/pdfjs-dist@2.5.207/build/pdf.min.js&quot;&gt;&lt;/script&gt;</pre><pre>&lt;script src=”https://cdn.jsdelivr.net/npm/pdfjs-dist@2.1.266/web/pdf_viewer.min.js&quot;&gt;&lt;/script&gt;</pre><p>Once these scripts are added properly we should have `pdfjsViewer` and `pdfjsLib` available in the global scope.</p><p><strong>**Note:**</strong> Make sure we get it right, before we move ahead</p><p>Now we will create a React component called `PdfPreview`.</p><p>Let’s see the boiler-plate code for the `PdfPreview` component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97b9f83d3c707d982ad301837c37df27/href">https://medium.com/media/97b9f83d3c707d982ad301837c37df27/href</a></iframe><p>This component takes in three props:</p><pre>docUrl: String -&gt; It is the pdf URL.</pre><pre>uniqueContainerId: String -&gt; It is uniqueContainerId</pre><pre>styles: Object -&gt; styles need to appended to the base styles</pre><p>Take some time to go through the code above. Nothing fancy just some JSX and an useEffect.</p><p>We need to add pdf preview initialization inside useEffect.</p><p>Now let’s add Mozilla pdf.js code copied from their [example folder](https://github.com/mozilla/pdf.js/blob/master/examples) with slight changes. The changes made are just to accomodate handling when pdf Url itself is not there or not valid.</p><p>The code below can seem daunting at first, but most of it is just handling the pdf preview various case and updating UI. I have copied most of the content directly from mozilla pdf.js examples. They have done a splendid work by putting up great examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f052c56cd51b25d08588ff5751459d3/href">https://medium.com/media/2f052c56cd51b25d08588ff5751459d3/href</a></iframe><p>If everything worked you should see the pdf rendered properly.</p><p>But you all must be thinking :</p><blockquote>Dude , without <strong>Demo</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQGZBpodY7Kdtw99y04%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQGZBpodY7Kdtw99y04%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQGZBpodY7Kdtw99y04%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="396" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51edb07a0bf022e0dcf25a7b44f600c/href">https://medium.com/media/a51edb07a0bf022e0dcf25a7b44f600c/href</a></iframe><p>Ohh alrighty !! Here is your demo below. Feel free to check the code, fork it and play with it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpractical-firefly-i5yly%3Fautoresize%3D1%26fontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fpractical-firefly-i5yly%3Fautoresize%3D1%26fontsize%3D14%26hidenavigation%3D1%26theme%3Ddark%26view%3Dpreview&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fi5yly%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/4819d66bb1f68d76b957dd599c6e4966/href">https://medium.com/media/4819d66bb1f68d76b957dd599c6e4966/href</a></iframe><p>I spent more than 6–7 hours to find out the solution. I hope someone who finds it will not.</p><p>The best part of this solution is now it is supported across devices and modern browsers.There will be surely be certain browsers where it might fail, but haven’t found any yet.</p><p>Tested it on mozilla(82.0.3 (64-bit)) , chrome(Version 87.0.4280.141), safari (Version 13.1.3 (15609.4.1)) for both desktop and mobile versions.</p><p>I wrote this article for my future self and for others, because I know that pdf preview is very common use case and will comeback often.</p><p>This pdf previewer for react is not packaged yet. May package it if I get good response or someone else can try it doing.</p><p>Thanks</p><p>Best of luck</p><p><strong>Helpful Links</strong> :</p><ul><li>There are no good Reactjs ports available. There was <a href="https://github.com/mikecousins/react-pdf-js/blob/master/README.md">react-pdf-js</a> library , but was very restrictive in the way it can be used.</li><li><a href="https://github.com/mozilla/pdf.js">https://github.com/mozilla/pdf.js</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2a47f2b733" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/solving-pdf-preview-nightmare-3f2a47f2b733">Solving Pdf Preview Nightmare</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QRCode Scan with Reactjs]]></title>
            <link>https://medium.com/swlh/qrcode-scan-with-reactjs-ef606babeded?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef606babeded</guid>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Sat, 23 Jan 2021 18:01:59 GMT</pubDate>
            <atom:updated>2021-01-25T15:09:12.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jic8w0iGQqG4rU-Z" /></figure><p>Photo from <a href="https://unsplash.com/@proxyclick">https://unsplash.com/@proxyclick</a></p><p>QrCode is a common way of sharing information without getting into long URLs. Most common of them which everybody must have used are how we make payments todays. Payment infrastructures like <em>GPay, UPI, PAYtm, PapPal</em> e.t.c , all make use of QRCode scanning for easy payment process. Today you go to any shop, you can find payment QRCodes in most of the places.</p><p>Recently I had a a problem statement of implementing QRCode scan for web (desktop and mobile both) .</p><blockquote><em>I thought that should be easy and readily available.</em></blockquote><h3>Expectations</h3><p>Let’s see what were my <strong>expectations</strong> with a qrcode scanning solution in reactjs.</p><ol><li>It should be a simple named import in my code.</li><li>It should work deterministically for almost all the time.</li><li>It should handle the cases when camera access is not there or camera is itself not there.</li><li>It should work across mobile browsers and web browsers atleast the major ones. (safari, chrome, mozilla, edge). Why I am specifing mobile browsers ? Because most of the time qr code scanning will be done via mobile phone’s camera.</li></ol><h3>Am I asking too much ?</h3><p>Some of you might say :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FfRc4IDQktRMAupJbnY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FfRc4IDQktRMAupJbnY%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FfRc4IDQktRMAupJbnY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdda4368f0b0e83c0e453c76b6e39a0c/href">https://medium.com/media/bdda4368f0b0e83c0e453c76b6e39a0c/href</a></iframe><p>Let’s start the adventure now keeping in mind the above expectations.</p><p>I made use of follwing <a href="https://github.com/mebjas/html5-qrcode#readme">html5-qrcode</a> library for qrcode scanning. <a href="https://github.com/mebjas">mebjas</a> created this wrapper around <a href="https://github.com/LazarSoft/jsqrcode">jsqrcode</a> which is a port of <a href="https://github.com/zxing/zxing">zxing</a> written in java.</p><p>Whoaa !! so many people are involved to bring qrcode scan to web. They truly deserve the applaud.</p><p>First step is to include <strong>html-qrcode.min.js</strong>(from the library) as the part of index.html. There are two ways of doing it.</p><ol><li>Add the following script tab above your end body tag.</li></ol><pre>&lt;script src=&quot;https://raw.githubusercontent.com/mebjas/html5-qrcode/master/minified/html5-qrcode.min.js&quot;&gt;&lt;/script&gt;</pre><p>2. Add it via using npm.</p><pre>yarn add html5-qrcode</pre><p>I am going to show how i did it for an App bootstrapped from c<a href="https://facebook.github.io/create-react-app/docs/getting-started">reate-react-app </a>which is ejected. For non-ejected mode continue reading.</p><p>We basically want to load html5-qrcode.min.js into the topmost context when your page loads in the browser. So that we can get the constructor function defined in the libary available on the window object. why so ?</p><p>Because the library is structured in this fashion.</p><p>We will make use of two webpack plugins to do so</p><p><strong>RUN</strong></p><pre>yarn add copy-webpack-plugin --dev</pre><pre>yarn add html-webpack-tags-plugin --dev</pre><p>Add following lines to config/webpack.config.js</p><pre>const HtmlWebpackTagsPlugin = require(&#39;html-webpack-tags-plugin&#39;);</pre><pre>const CopyWebpackPlugin = require(&#39;copy-webpack-plugin&#39;);</pre><ol><li>HtmlWebpackTagsPlugin is used to add a script tag in the template html(index.html)</li><li>Copywebpackplugin is used to copy the html5-qrcode.min.js from node_modules to build folder.</li><li>In the webpack plugin section add following section:</li></ol><pre>new CopyWebpackPlugin({<br>  patterns: [<br>    {<br>      from: &quot;node_modules/html5-qrcode/minified/html5-qrcode.min.js&quot;,<br>      to: `static/js/html5-qrcode.min.js`,<br>    },<br>  ],<br>});<br>new HtmlWebpackTagsPlugin({<br>  tags: [&quot;/static/js/html5-qrcode.min.js&quot;],<br>  append: true,<br>  publicPath: false,<br>});</pre><p>For apps which are in non-ejected mode , make use of <a href="https://www.npmjs.com/package/@craco/craco">https://www.npmjs.com/package/@craco/craco</a> to customize the webpack config using the steps above.</p><p>Once all this is done, when you run you app , you should be able to see Html5Qrcode in the global scope. Just type Html5Qrcode in the console and you should see something.</p><blockquote>If you are not seeing Html5Qrcode available in console. Don&#39;t move ahead, nothing will help in upcoming sentences. Please try to fix it.</blockquote><h3>Are we done yet ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*i1lvZQ0DBlHO00Ru.gif" /></figure><p>Exactly, it took me a lot more time. Just keep reading till we get the whole thing right.</p><p>Let’s create a custom hook which takes cares of starting the html5qrcode scanning, parsing the data and giving back the result or error information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3655c20cac7b86cfc9d7e3c6cad05a98/href">https://medium.com/media/3655c20cac7b86cfc9d7e3c6cad05a98/href</a></iframe><p>The custom hook takes qrcodeMountNodeID(html element id) where the camera will be mounted. That is mandatory. If you are not passing qrcodeMountNodeID code might fail.</p><p>It also gives back you the function startQrCode which can be called to start the qrcode scanning. You can also programatically close the qrcode by calling stopQrCode. Better way of doing can be to just remove the qrcodeMountNodeID node from the html.</p><p>Now to use the above custom hook, you can have a sample code like this:</p><pre>const { startQrCode, decodedQRData } = useQRCodeScan({<br>  qrcodeMountNodeID: &quot;qrcodemountnode&quot;,<br>});</pre><p>In your JSX</p><pre>&lt;div id=&quot;qrcodemountnode&quot;&gt;&lt;/div&gt;</pre><p><strong>Note</strong>: Make sure you have a DOM node with id qrcodemountnode before you start the scaning.</p><p>Once you have access to startQrCode you can call it either on button click , or on mount of the component or any other way.</p><h3>How I did it ?</h3><p>I kept the qrcodemountnode html element in a modal. On click of some button, I am opening the modal. Modal is making use of useQRCodeScan hook. On mount of the component I am making a call to start the camera and start scanning.</p><pre>useEffect(() =&gt; {<br>  // Add logic to add the camera and scan it<br>  startQrCode();<br>}, []);</pre><p>Whenever the scan is successful, you will get the data in decodedQRData, which can be read by your component to trigger either an API or any action.</p><h3>But then does the story ends here ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*3OH-FapwPE6kEX_L.gif" /></figure><h3>Development Challenges</h3><p>There are some facts which i came to know, when doing development.</p><p>First the camera access will only be allowed for https connections.</p><p>OK , so how do we do that in CRA</p><p>Just start the server like this :</p><p><a href="https://create-react-app.dev/docs/using-https-in-development">HTTPS in development</a></p><p>Next one was, How do you test in the phone ?, while doing development on the laptop. You can’t be waiting for the deployment to happen to some environment first and then do the testing.</p><p>To get around this: I ran following command in the terminal to find out the my laptop ip address.(Mine is mac machine, for window and various linux distros it can be different).</p><pre>ifconfig</pre><p><strong>Note:</strong> Make sure your laptop and phone are connected to same internet</p><p>Once you have the IP, you can open the application in phone browser. If you are running the server at https://localhost:3000 and let&#39;s say your machine ip is 192.168.43.56, then open https://192.168.43.56:3000 in your phone.</p><p>This should open the application successfully. But will it ?</p><p>It definitely opens the application successfully, but with one problem (at least in my case). There was the problem in a way we were setting cookies. The cookies were still being tried to set for localhost on my phone. One domain cannot set the cookie for some other domain. Why it was happening in my application ?</p><p>We were reading domain from .env file to set the auth cookies. To fix it I also added the code to set the cookie for 192.168.43.56 domain. (only for development, removed before pushing it to git).</p><p>Lastly , how will we debug the app running in your phone ? I mean how we will see the console.log statement in phone. I didn’t find any solution there. So to get around that, I tried maximum of things on laptop only. But for testing decoded value, I kept a DOM node to hold the parsed result.</p><h3>Notable moments:</h3><ol><li>You can also scan the QR code from laptop camera , just by putting a qrcode image in front of it.</li><li>If the image is not clear, sometime the decoded value will not be something which you expected. So please validate the decoded value of a qrcode.</li><li>I once thought to implement qrcode scanner on my own , then realized there is a lot of mathematics, logic and genius involved. I cannot implement it on my own or atleast in a finite time.</li></ol><p>If you are able to create a qrcode scanner using this article. Scan the below qrcode to follow me. Don’t use any readymade qrcode scanner 😜</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*fyKYp8mS2MUODPCe.png" /></figure><p>Best of luck !!</p><p><em>Originally published at </em><a href="https://simbathesailor.dev/qrcode-scan-web-reactjs/"><em>https://simbathesailor.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef606babeded" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/qrcode-scan-with-reactjs-ef606babeded">QRCode Scan with Reactjs</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Custom Terminal Commands]]></title>
            <link>https://simbathesailor007.medium.com/create-custom-terminal-commands-bd4485d5488a?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4485d5488a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Thu, 31 Dec 2020 10:27:12 GMT</pubDate>
            <atom:updated>2020-12-31T11:33:41.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3k5l6yeHWPxtRtXc" /></figure><p><a href="https://unsplash.com/@hannahjoshua">Photos by hannah joshua</a></p><h3>TLDR:</h3><ol><li>Shebangs lines are added on top of command-line files. The line tells the system which executable has to be used to run the current file. The shebang line looks something like this:</li></ol><pre>#!/usr/bin/env node</pre><p>The above line means: Execute with a node interpreter, using the program search path to find it.</p><p>2. The System looks for command files or executables in all the directories pointed by PATH environment variable. You can also run different scripting executables using right shebang syntax.</p><p>3. So to have a valid command, mostly you need to have the executable file in one of the PATH directories and correct shebang for right executables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*hAZy_KdI1XPPIlgs.gif" /></figure><p>Ever wondered how custom commands works at all. 🕺 I wondered this today and took up the task to dig more into it.</p><blockquote><em>I will try to keep it simple because who doesn’t love simplicity.</em></blockquote><p>Before we start let’s define our end goal. We want to basically run a script from the command line using their name only !!</p><p>Let’s say we have a file named somework.js.</p><p>Let’s assume the only content of the file is:</p><pre>console.log(&quot;Hello World&quot;)</pre><p>How will you run in nodejs ?</p><p>You will run it something like : node somework.js</p><p>Now, If I want to run this script without the node command. Something like this:</p><pre>somework</pre><p>It should work the same way as it is working with node command. It should output Hello World in the terminal.</p><p>Let’s go and see various elements involved when you run a command.</p><h3>Shebangs</h3><p>I work mainly in javascript ecosystem, So I have a good enough idea about how commands are working. I knew that putting a bin field in the package.json and pointing to your script will be enough( <a href="https://docs.npmjs.com/cli/v6/configuring-npm/package-json#bin">Read more</a>).</p><p>I never went back to figure out what happens after that.</p><p>This time I did more like with this attitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ztTrKd1GbFGl4MYs.gif" /></figure><p>I started looking at one of the bin files in node_modules One thing I could see was a special line on top of the file, which looked something like this:</p><pre>#!/usr/bin/env node</pre><p>If you are having a nodejs application, go ahead and check any file in the node_modules/bin. You should find a similar line.</p><p>I felt this is interesting. I searched again. and landed to this <a href="https://en.wikipedia.org/wiki/Shebang_(Unix)">link</a>. These are called <strong>shebang | hashbang | pound bang | hash-pling</strong></p><p>Turned out shebang is <strong>interpreter-directive</strong></p><h3>Woahhhhhh!! 😲 😲</h3><p>But, What is <a href="https://en.wikipedia.org/wiki/Interpreter_directive"><strong>interpreter-directive</strong></a>? In simple words, it is just a way to tell the system how to react to the commands you enter ( what executable need to be run ?).</p><p>In simple words, if there is a line like this:</p><pre>#!/usr/bin/env node</pre><p>It means: Execute the file with a node interpreter, using the program search path to find it.</p><p>We know we want to run a nodejs file, hence we should add the line to the top of our file</p><p>The content of the file would have become:</p><pre>#!/usr/bin/env node </pre><pre>console.log(&quot;Hello World&quot;)</pre><p>Give executable permission to the file.</p><p><strong>RUN</strong></p><pre>chmod +x somework.js</pre><p>Will that be enough?</p><p>Remember there is one more part to it which</p><blockquote><em>Using the program search path to find it.</em></blockquote><p>What does that mean? Let’s see that in the next section.</p><h3>PATH</h3><p>We need to figure out how a system looks for executables. Again, I searched for it. and then came across this <a href="https://en.wikipedia.org/wiki/PATH_(variable)">link</a>.</p><blockquote><strong><em>Note:</em></strong><em> These are just the final links. In reality it took me much more time to reach to these links.</em></blockquote><p>Now coming back to business</p><p>As the definition says on Wikipedia:</p><blockquote><em>PATH is an environment variable on Unix-like operating systems, DOS, OS/2, and Microsoft Windows, specifying a set of directories where executable programs are located</em></blockquote><p>Hmm, great !! But how do we see what is the value of PATH right now in my system?</p><p><strong>RUN</strong> (Should work on Linux based Terminals)</p><pre>echo $PATH</pre><p>Note: For Windows OS, check the following <a href="https://superuser.com/questions/1216658/path-environment-variable-windows-10-echo-path-on-command-prompt-shows-only/1216663">link</a></p><p>You will get some sort of this as an output:</p><pre>/Users/wolfgupta/.nvm/versions/node/v14.15.3/bin:/Applications/mongo/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Library/Apple/usr/bin:$GOPATH/bin:$GOROOT/bin:/Users/wolfgupta/Library/Android/sdk/emulator:/Users/wolfgupta/Library/Android/sdk/tools:/Users/wolfgupta/Library/Android/sdk/tools/bin:/Users/wolfgupta/Library/Android/sdk/platform-tools:/usr/local/mysql/bin</pre><p>These are set of directories, which are looked up for the files having the same name as the command. The files(somework.js) can contain logic.</p><p>This should be a very simple search on google. I will leave this task to you guys.</p><p>Here are some of the links which you might find useful.</p><ul><li><a href="https://stackoverflow.com/questions/24219627/how-to-update-system-path-variable-permanently-from-cmd">How to update system PATH variable permanently from cmd?</a></li><li><a href="https://www.architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.Uydjga1dXDg">Add to the PATH on Mac OS X 10.8 Mountain Lion and up</a></li></ul><p>If you are using macos / linux . Changing ~/.bashrc , ~/.zshrc e.t.c should do.</p><p>If you really want to check other common nodejs command definitions that you use on a daily basis.</p><p><strong>Run</strong></p><pre>cd /usr/local/bin<br>ls</pre><p>you can do vi to any of the file listed to understand the commands better</p><p>Now to convert node somework.js to somework. we will first <strong>rename</strong> the file to just somework without extension and then move it to /usr/local/bin</p><p><strong>Run</strong></p><pre>mv ./somework /usr/local/bin</pre><p>Now, just close the current terminal tab and open a new tab.</p><p><strong>Run</strong></p><pre>somework</pre><p>You should see your beautiful Hello World printed on the terminal.</p><p>This is about node, how about if you are a python guy and want to write your script in python. You can very well do it with the help of shebangs</p><p>Change the content of the file in somework file at /usr/local/bin to</p><pre>#!/usr/bin/env python</pre><pre>print(&quot;Hello World!&quot;)</pre><p>Note: Make sure you have python installed in your machine.</p><p>In this file, you can write any python script and will work how nodejs version of the file was running.</p><p>There are so many other details which I am not mentioning here. But yes, you can definitely have this article act as a good starting point to create command-line utilities for your software.</p><p>Finally, Wishing a great new 2021 to all of you. May the world be a better place for all of us in the coming years.</p><p><a href="https://twitter.com/simbatheesailor">Anil Chaudhary</a></p><p><em>Originally published at </em><a href="https://simbathesailor.dev/custom-terminal-commands/"><em>https://simbathesailor.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd4485d5488a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A better alternative to useEffect]]></title>
            <link>https://medium.com/weekly-webtips/a-better-alternative-to-useeffect-420737670211?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/420737670211</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 17:01:01 GMT</pubDate>
            <atom:updated>2020-08-25T06:27:25.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Better Alternative to useEffect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DW2sTbM9H7Eb1iTC" /><figcaption>Photo by <a href="https://unsplash.com/@avery_james?utm_source=medium&amp;utm_medium=referral">Avery Morrow</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>My experience with <a href="https://reactjs.org/docs/hooks-intro.html">React hooks</a> have been amazing. In this article, I will precisely talk on one of the most prominent hooks that we use on a daily basis which is <strong><em>useEffect.</em></strong></p><p>I am assuming the readers coming to this article has good understanding on useEffect. If not, please first go through the concept at <a href="https://reactjs.org/docs/hooks-reference.html#useeffect">reactjs.org</a>.</p><p>So essentially, <strong><em>useEffect</em></strong> react to changes in dependency list. They have replaced <strong><em>componentDidMount, componentDidUpdate, componentWillUnmount and componentWillReceiveProps in </em></strong>class based react components.</p><p>It’s very common to react to changes in props values or state values over the lifetime of a component. we also need to compare previous values and current values when reacting to changes often. In the class based component, we had <strong><em>componentDidUpdate</em></strong> for the similar use-cases.</p><p>It has following interface:</p><pre><strong>componentDidUpdate(prevProps, prevState, snapshot)</strong></pre><p>You have access to <strong><em>prevProps(previous props)</em></strong> and<strong><em> prevState(previous state)</em></strong>, which can be used to make comparisons and react appropriately.</p><p>What about useEffect, how would you do those kind of comparison with them?</p><h3>Solution 1</h3><p>You can have a <strong><em>usePrevious</em></strong> custom hook which will always give you the previous value and that you make use in your useEffect to complete the comparison. Let’s see some code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkeen-lovelace-t27gj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fkeen-lovelace-t27gj%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft27gj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba824ebedd4c244e1b2190db5251d77c/href">https://medium.com/media/ba824ebedd4c244e1b2190db5251d77c/href</a></iframe><p>Notice, how <strong><em>usePrevious</em></strong> hook helps us by keeping a track of previous value. Now think about scenario, when there are more than one dependency in our useEffect. We need to make use of <strong><em>usePrevious </em></strong>hook that many times or we have to re-define our <strong><em>usePrevious</em></strong> hook to track an array of dependency.</p><blockquote><strong><em>Isn’t it too much of work every time ?</em></strong></blockquote><p><strong><em>Can we have something similar to componentDidUpdate ? We can have previous and current values of the dependencies as the argument of the callback of useEffect.</em></strong></p><p>That could save us a lot of time while working with update scenarios in useEffect hook.</p><h3>Solution 2</h3><p>I was able to package everything in a npm package, which can act as a drop in replacement for useEffect anywhere. I call it <strong><em>useEffectX. </em></strong>Let’s see the the same example we showed in above codesandbox with<strong><em> </em></strong>our shiny new<strong><em> useEffectX.</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fancient-frog-t7tc0%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fancient-frog-t7tc0%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft7tc0%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8706cbd2a3f138a3cf5a0a0f8d13db/href">https://medium.com/media/2c8706cbd2a3f138a3cf5a0a0f8d13db/href</a></iframe><p>Notice now , how we have access to previous values in the arguments of useEffectX’s callback itself. We don’t need any usePrevious hook now plus the arguments are completely optional same with any function. The code snippets below will also work exactly same as official<strong><em> useEffect</em></strong></p><pre>useEffectX(() =&gt; {<br>  console.log(val, someotherVal)<br>}, [val, someotherVal])</pre><pre>useEffectX(() =&gt; {<br> console.log(&quot;do something after every render&quot;)<br>})</pre><p>Thanks. Please let me know , what you all think about this <strong><em>useEffectX.</em></strong></p><p><a href="https://github.com/simbathesailor/use-effect-x">simbathesailor/use-effect-x</a></p><p><a href="https://twitter.com/simbatheesailor">https://twitter.com/simbatheesailor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420737670211" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/a-better-alternative-to-useeffect-420737670211">A better alternative to useEffect</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Talk to React components from outside React]]></title>
            <link>https://simbathesailor007.medium.com/talk-to-react-components-from-outside-react-6d195cd9297?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d195cd9297</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 18:08:11 GMT</pubDate>
            <atom:updated>2020-08-06T18:08:11.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M3zOA5rrt6i-7fk1" /></figure><p>What if I have to control the react components from non-react codebases ? Let me re-phrase it with some concrete scenario.</p><p>What if I need to open a react modal from non-react codebase like utils functions, fetch wrapper e.t.c</p><p>This is such a common use case. We want to show the modal, then and there , when some condition passes. That condition can be in a non-react codebase.</p><p>Let see how we can do it.</p><p>All the modern applications, make use ES6 modules and they have live bindings. These live binding can be really useful when accessed from other files (any file react component or outside react component)</p><p>What is a live binding can be understood quickly by seeing the answer to <a href="https://stackoverflow.com/questions/52211309/what-does-it-mean-by-live-bindings">this</a> stackoverflow question.</p><blockquote><em>Make sure you understand the above stackoverflow answer before diving ahead.</em></blockquote><p>As we asked the question in context of a modal in the start, let’s start with some modal code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0164f2ce216acfadd1513e85fc0767ff/href">https://medium.com/media/0164f2ce216acfadd1513e85fc0767ff/href</a></iframe><p>Modal component is a not important here as it is a usual modal making use of react portal.</p><p>But notice , line no. 30, where I have declared and defined a variable toggleModal outside ModalFromOutsideReact. The component ModalFromOutsideReact has the access to the toggleModal from inside the component (Javascript closures at play here) and I can also change the value of toggle modal from inside the component.</p><p>So on the every re-render of this component, we can update the toggleModal with some state setter (or anything).</p><p>But in this example we can set it to the function below, which takes care of toggling the modal show/unshow</p><pre>toggleModal = ( showVal, dataFromAPI ) =&gt; { setData (dataFromAPI) setShow (showVal) }</pre><p>Now whenever the show value is truthy in the components, modal will show up.</p><p>We need 2 more steps to achieve our goal</p><p>We need to add this components somewhere in the APP react hirerarchy , possibly at the very top in this specific case.</p><p>Let’s say I have App.js which is at the very top in the App React hirerarchy. I can safely render the ModalFromOutsideReact component unconditionally here Rendering in the App.js will make sure that the toggleModal is instantiated before any other component gets render in our App</p><p><em>App.js</em></p><pre>import ModalFromOutsideReact from &quot;path/to/ModalFromOutsideReact&quot;;<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;ModalFromOutsideReact /&gt;<br>      // Rest of the APP<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Secondly we need to export the toggleModal from ModalFromOutsideReact. See the line no. 70 in github gist</p><p>Now, you are all set to trigger the modal from anywhere in the app, be it React component, non-react codebases like fetch wrappers, utils e.t.c.</p><p>You are not forced to go through all your component render cycle to show a modal. you can declaratively do that now.</p><p>This example is pretty basic and can be improved a lot. But the core idea was to demonstrate the how’s of interaction between react and non react world.</p><p>Thanks</p><p>Feel free to connect with me on <a href="https://twitter.com/simbatheesailor">https://twitter.com/simbatheesailor</a></p><p><em>Originally published at </em><a href="https://simbathesailor.dev/how-to-trigger-react-components-from-outside-react/"><em>https://simbathesailor.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d195cd9297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlled components with React hooks]]></title>
            <link>https://medium.com/weekly-webtips/controlled-components-with-react-hooks-58a2134a7100?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/58a2134a7100</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 05:39:31 GMT</pubDate>
            <atom:updated>2020-06-25T19:40:13.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*-bFWYpsNvJ2IJL5a" /></figure><p>I love controlled components. Do you ?. Such a cliche question, but anyways let’s talk about controlled components with hooks.</p><p>They make your components flexible. They also help you keep a single source of truth for your component’s data.</p><p>You never want to mix controlled and uncontrolled components. More on this here <a href="https://reactjs.org/docs/glossary.html#controlled-vs-uncontrolled-components">React controlled vs uncontrolled</a>.</p><p>Controlled components are better when thinking in react mindset. That way you don’t have to think about the UI updates. React gives you the guarantee that UI shown to you is in-sync with your data in almost all the cases.</p><p>But creating controlled components and consuming them every time, comes up with some tradeoffs. You orchestrate the data in one of the higher components that renders a controlled component. Don’t worry if the prior lines were a bit confusing. Let’s understand this with a diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AlXnww91uSgdVfPlc2iXA.png" /></figure><p>In the diagram, we have one modal having a search box and a result section. There are two data points here:</p><ol><li>Search value in the input.</li><li>The data item array which is used to render cards.</li></ol><p>This kind of modal having similar search and results is needed at multiple locations in our application.</p><p>And every place the post search logic varies. And once you have results with you, there are different logic post that. A few places you also need to set the search value programmatically, on some updates.</p><p>Now, this is definitely a made-up situation here. But this scenario is so common in real applications.</p><p>To keep this UI completely re-useable, we will go for controlled components, remember I told you that I love controlled components and by now I can assume, that you love it too.</p><p>Let’s try to write a component hierarchy for this situation.</p><pre>&lt;AnyofyourComponent&gt;<br>  &lt;SearchAndResultView&gt;<br>    &lt;Modal&gt;<br>      &lt;SearchBox /&gt;<br>      &lt;ResultContainer /&gt;<br>     &lt;/Modal&gt;<br> &lt;/SearchAndResultView&gt;<br>&lt;/AnyofyourComponent&gt;</pre><p>This will be the rough hierarchy, we will talk in the rest of the article</p><p>I will not go very deep into the controlled component. But let me give you some understanding about it.</p><blockquote><strong><em>Controlled components</em></strong><em> keeps the control of data with React. They rely on React to update UI in-sync with the data available to the component.</em></blockquote><p>Read more about it here <a href="https://reactjs.org/docs/forms.html#controlled-components">Controlled components</a></p><p>And then there are <strong>uncontrolled components</strong>. which takes matter into their own hand. They imperatively change the rendered result properties. <a href="https://reactjs.org/docs/uncontrolled-components.html#gatsby-focus-wrapper">Uncontrolled components</a></p><p>There is one more way to see uncontrolled components. Now let’s say you have a component that keeps the data with itself and the parent does not have access to it. The child component itself is in control of data and the parent can’t essentially change the child component’s state. In this scenario, the child component is not designed in a way where you can control the outcomes in the child component and it will also hamper the reusability. Opposite of it is controlled component</p><p>So in our case, if the search state and result state is with the SearchAndResultView component, it becomes an uncontrolled component.</p><p>But if the values needed to render the SearchAndResultView are coming from the parent component, we get a controlled component.</p><p>Let’s see how a parent component will use this child component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/011e7e259baa10ab275056f759d27054/href">https://medium.com/media/011e7e259baa10ab275056f759d27054/href</a></iframe><p>Note: There are better ways of organizing the current component hierarchy, but let’s focus on only the controlled component stuff.</p><p>Notice, what all we needed to do to make use of SearchAndResultView.</p><p>We have to have two states, one for search and one for the result. In some scenarios, these kinds of definitions become so big and scattered. Next time you try to use the component, it eats away your whole time</p><p>We have to do a similar kind of thing everywhere we are using this SearchAndResultView component.</p><p>This is how fundamentally controlled components system works in reactjs. There is nothing wrong with it. But, Can we remove this repeated work?</p><p>Yes we can, that’s why this blog 😄</p><p>Now let’s observe the below snippet</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1424977d5940b14be7208b245434f2c/href">https://medium.com/media/c1424977d5940b14be7208b245434f2c/href</a></iframe><p>Notice, how the statements for defining states are now moved to <strong>useSetup</strong> hook. Now, every component that wants to use the SearchAndResultView doesn’t have to write the state definitions first to use the controlled component.</p><p>They can make use of the controlled component’s <strong>setupHook</strong></p><p>This way of writing controlled components have surprisingly improved my experience of working with controlled components. It’s a simple, but yet powerful way of writing components in Reactjs. This could not have been possible without React hooks.</p><p>You have complete control to change the value of the SearchAndResultView component anytime you like. This way we have all the controlled component benefits and also the ease of use.</p><p>Thanks</p><p><em>Originally published at </em><a href="https://simbathesailor.dev/controlled-component-and-hooks/"><em>https://simbathesailor.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58a2134a7100" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/controlled-components-with-react-hooks-58a2134a7100">Controlled components with React hooks</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build front-end apps once & reuse across environments]]></title>
            <link>https://medium.com/sequoia-com/how-to-build-front-end-apps-once-reuse-across-environments-fffbae5f2dec?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffbae5f2dec</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[babel]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Mon, 04 May 2020 07:30:41 GMT</pubDate>
            <atom:updated>2022-01-18T07:52:53.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVu4AEV4Owq7oEuJF4XGQA.png" /></figure><p>A beautiful afternoon, working on regular stuff. Everything was going smoothly. Then a notification pops up on my screen saying `Hi`</p><p>who’s that?</p><p>Found out it was our DevOps Architect. I replied `Hi`. I thought he pinged me for some regular build related query.</p><p><em>We will be calling Our DevOps Architect as D.A in the rest of the article.</em></p><p>But next ping was a start to a very interesting problem and at the same time challenging.</p><p>He asks me this question</p><blockquote>Can we separate the env generation part and the build process? , so that we can use the same docker image for various environments.</blockquote><p>Before I move on to my reply. Let me give you some more context. So generally for most of the frontend applications. We keep endpoints, analytics keys, and other keys at a cloud-based key-value pair store. These parameter store values are fetched before building for any environment(dev, staging, UAT, pre-production e.t.c). We fetch these param values and set them to process.env</p><pre>process.env.REACT_APP_PARAM_ONE={SOME_VALUE_FROM_PARAMSTORE}</pre><p>By doing this, we make these values available in our build process. This leads to the creation of a build folder containing correct param values. That’s the process we almost always follow.</p><p>Moving on to the conversation</p><p><strong><em>Me</em></strong>: The env generation part cannot be done after the build is done. Because by the time build is done, all the param values are already in your bundle code. There is no way of injecting environment-specific values later on.</p><p>But then, He has already done a good amount of research around this topic. I was not ready enough. So we started having more conversations.</p><p><strong><em>D.A</em></strong>: What about backend ?. They are able to successfully do it. We are able to use the same build for various environments.</p><p>I gave a thought for some minutes and then</p><p><strong><em>Me</em></strong>: Well, for them it is quite easy to do so, as their’s code runs on the server-side, where they can keep picking param values from memory(RAM). But for frontend apps, where we statically build, bundle code, and ship it to user browser, it is no way possible. For frontend apps <strong>Run Time </strong>itself is not there on the server, it’s in the user’s browser.</p><p><strong><em>D.A</em></strong>: Ok. But right now we are repeating the build process in all the environments for the same code. This is not optimal. We need to find a way for that separation.</p><p><strong><em>Me</em></strong>: Yes, definitely. I understood the problem. Give me some time to think about it.</p><p>Our <strong><em>D.A</em></strong> in the meantime searching all on the web for all the relevant articles on this topic.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FULR7kNP2lhJXW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fbruce-almighty-ULR7kNP2lhJXW&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FULR7kNP2lhJXW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d002d12e0887f17850febe49dd6cfc2/href">https://medium.com/media/9d002d12e0887f17850febe49dd6cfc2/href</a></iframe><p>He came up with a few articles and threw them at me in the chat.</p><blockquote>Actually it’s always a difficult scenario when a team member tells you that it is easy peasy. It might look easier from the outer perspective. Instead of going into defence mode, you have to come up with a justifiable reason, why something can’t be done in your scenario.</blockquote><blockquote><strong>Healthy crucial conversations always leads to innovation.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUC2teBPEhDA9bS9iSsPzg.png" /></figure><p>I have learned this hard way and thought to convert this problem into an opportunity to innovate. When we work together as a team and practice positive criticism, we grow. I should thank our DevOps Architect in this case for pushing me into figuring out a solution to our problem.</p><p>So now, I thought well, let’s read these articles. They actually helped me to visualize the solution at hand with more clarity, but the solutions mentioned were either non-generic or non-secure.</p><p>For example. Putting a separate .js file per environment in your hosted folder is not at all a safe idea. Because once they are loaded on the client-side, they need to be added in the global scope to allow their access everywhere. But the global scope is available for each and every script. Any third party script can update the param values and steal the data. if needed.</p><p>By this time, I was very clear about my goals for this problem. Let’s highlight them below.</p><ul><li>The solution should not change the way developer write code.</li><li>The Developer experience should not hamper at any cost.</li><li>Most of the build process work needs to be reused except param value injection which is environment-specific.</li><li>It should be blazing fast. (consecutive builds).</li><li>The solution should be very generic at the conceptual level. More on this later.</li></ul><p>So now we know the high-level goals.</p><h3><strong>How it works</strong></h3><p>This all happened over the span of 2–3 days. By then, I have got some ideas and was able to draw the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmqK0pjRr0WRzIcMwpeH0w.png" /><figcaption>Problem Statement</figcaption></figure><p>Now the REACT_APP_TEST will be replaced with `<a href="https://some/envspecific/api">https://some/envspecific/api</a>` after the production build. But the Param value is specific to the staging environment. We can’t use the bundle generated after step1 for another environment. We have to repeat the complete build process for all the environments. This is the problem statement.</p><p>Now, what if we can make use of the bundled code without building again for various environments. How cool that would be !!. We will save a lot of time, network bandwidth and processing on our servers. I started thinking 🤔</p><p>If we are able to prevent the param values to replace in the build process, we can get a second step where we can just inject these param values. Injecting param values will take a minimal amount of time, but all the heavy lifting done by the build process will not be repeated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmSYrZPga5EFdOTwu7IN0A.png" /><figcaption>Solution</figcaption></figure><p>So as we can see above, The desired process was to allow a second step where we do the injection. All good on theory. But How do we do it?</p><p>Our project uses webpack and it is responsible to bundle the code. We have to tell webpack to not transform and evaluate certain values.</p><p>The examples of types of values are :</p><pre>process.env.REACT_APP_NAME<br>process.env[“REACT_APP_PARAM_ONE”]</pre><pre>&lt;div className=&quot;App&quot;&gt;<br>  {process.env[&quot;REACT_APP_PARAM_THREE&quot;] === &quot;I AM PARAM THREE&quot; &amp;&amp; (<br>    &lt;p&gt;Conditional got rendered&lt;/p&gt;<br>  )}<br>&lt;/div&gt;;</pre><p>webpack uses babel for loading .js files in our project. It is responsible to transpile our code to a module ES5 output.</p><blockquote>So this article is more on usage of the solution rather than the complete implementation. We will be covering usage of packages created in the whole process thoroughly and leave an opportunity for another article if needed.</blockquote><p>So I ended up creating a webpack loader which makes use of babel parser to replace the param value with some placeholder values giving us a second chance for replacement.</p><p>The second step surely needs some kind of script which does the correct replacement of values. To address all this, I ended up creating a GitHub repo and npm package. Here is the link to those:</p><p><a href="https://github.com/simbathesailor/envvarprep-loader">simbathesailor/envvarprep-loader</a></p><p>The link to npm package is :</p><p><a href="https://www.npmjs.com/package/envvarprep-loader">envvarprep-loader</a></p><p>The readme file is updated with the latest docs, can be referred for the usage.</p><p>Finally, I was able to make use of the same build across multiple environments. I will be updating this post on the final improvements in deployment times within a few days.</p><p>One learning everyone can take with this story is, how a problem can be a beautiful chance for learning and doing new things. These problems are the reason for innovations. Challenge your problems and that too with positiveness. Things will fall your way.</p><p>We at Sequoia Consulting Group, believe in a culture where we push each other for innovation to build world-class products.</p><p>Reach out to me to know more about the team and the culture. Surely check out our career page</p><p><a href="https://www.sequoia.com/about/careers/">Careers at Sequoia</a></p><p>Thanks !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffbae5f2dec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sequoia-com/how-to-build-front-end-apps-once-reuse-across-environments-fffbae5f2dec">How to build front-end apps once &amp; reuse across environments</a> was originally published in <a href="https://medium.com/sequoia-com">Sequoia.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Patterns with React hooks]]></title>
            <link>https://simbathesailor007.medium.com/useful-patterns-with-react-hooks-a67a984d42f6?source=rss-b461f75fa84------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67a984d42f6</guid>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[useref]]></category>
            <dc:creator><![CDATA[Anil Chaudhary]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 12:41:46 GMT</pubDate>
            <atom:updated>2020-07-16T07:56:45.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nJLkAHTH68MGsDbi" /><figcaption>Photo by <a href="https://unsplash.com/@abeso?utm_source=medium&amp;utm_medium=referral">Sebastian Bednarek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Well, here I am explaining the pattern in React hooks. Who am I ? No body !! Don’t be mad because this is opinionated. Things which worked for me and the people around me.<br>That’s it.</p><p>First let’s take a step back, and understand what changed with react hooks. Well, A lot has changed but we will talk about those things which are going to be relevant for the the discussion ahead.</p><p>From now on I will be calling React hooks as just hooks. I am tired of adding React in front of every hook word :).</p><p>So the hooks come with a beautiful way of sharing stateful logic between components and also make the reusability of logic much easier. The hooks allows to segregate the logical concerns properly. Remember how we were adding a functionality spread across various lifecycle methods with classes approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be1e39c73ea65d2a6fdc6bec29137ca4/href">https://medium.com/media/be1e39c73ea65d2a6fdc6bec29137ca4/href</a></iframe><p>It is all good, but problem starts when we think how do we share the logic to other components. we then use to take on HOC patterns and render props pattern, which are very good patterns for sharing the logic. But with all goodness, they also bring lot more not needed verbosity and false hierarchy of our components. It also bring in friction to extract reusable logics.<br> <br>We will not discuss more on class based components. Because I think you are here to see the patterns with hooks and some food for thought.</p><p>Hooks are very good, but there are certain thing which can make situations difficult for even a seasoned developer. One of the problem which I used to encounter is with the custom hooks. A simple custom hooks is quite straight forward to work on. But its start’s getting confusing when it takes multiple arguments.</p><p>Even multiple arguments are good, but when the argument are objects, array or functions , It becomes very difficult to wrap your head around the hook.<br>Yes, React has provided certain hooks which allows me to mix and match them and solve the issue. I felt myself putting in a lot of focus and head while writing a custom hook which now has started accepting functions. Damn why I have to be so cautious. Why I can’t just pass functions as make it work. Why the infinite loops are getting triggered, why I have to every time think , Should I use useRef or useCallback ? At the time , I would be like</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FUQOjUuqeyIjAzJJ169%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FUQOjUuqeyIjAzJJ169%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FUQOjUuqeyIjAzJJ169%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/57e77ed3ca7721d315c97bf8828338a5/href">https://medium.com/media/57e77ed3ca7721d315c97bf8828338a5/href</a></iframe><p>Yes, but some would say ohh, so you are experienced and you are not able to figure out closures and references. Oh yes my friends, I find myself good with those concepts , but does not like the fact of thinking it every time ,when i am passing references to the hooks. For me custom hooks are just a utility that does processing and return back something which I use in my visual components.</p><p>So some might say, I have not felt that way. I am totally ok with how to write hooks. I would say cool, you have got it. May god teach all of us that finesse.</p><p>But before we see some code, let’s understand why objects, arrays and especially objects are little complicated with hooks.</p><p>My opinion is different for (object, arrays) and different for functions. I would say nothing has changed for objects and arrays as such. If we pass a new reference of arrays or object in class based component, the componentDidUpdate will get triggered. With hooks similarly, a hook with dependencies as arrays or object will rerun and do it’s thing.</p><p>But when it comes to functions we are so used to write them as component instance, that function does not change very often with class based component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/875c6e8817a6c3b819502f9c076f0ba5/href">https://medium.com/media/875c6e8817a6c3b819502f9c076f0ba5/href</a></iframe><p>Notice above how the Child component (SomeChildComponent) is taking two props:</p><pre>callback : available on instance, does not change on re-render<br>callback2: same as above</pre><p>But with hooks, there are no lifecycles now, mental model has changed to an extent.we still write the functions we need to pass on to other hooks or component inside the function. I think that comes natural. It means every time the component re-render the new reference is being passed to the respective hook or components.Btw It has benefits as we are having access to value outside due to closure. Could have been a dragged effort to pull the functions out of the components every time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3532bd465e78d53af7b1239ce17892c/href">https://medium.com/media/f3532bd465e78d53af7b1239ce17892c/href</a></iframe><p>Now for simple cases , it’s all ok, but as the logic progresses inside component and the components around it, it demands a lot of focus.</p><p>To the readers who are still with me, let’s see some code and understand various ways of handlings references with hooks. We will go through various cases and by the end we will have correct mental model and patterns to work with hooks. Take all these cases below as some of the ways of working with hooks , not all.</p><p>We will be taking small examples, base code will not change much across cases except certain parts of them. Every example will have base problem and the ways to fix it.</p><h4><strong>CASE 1:</strong></h4><p>Input</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35256ab3079573613eac2c8eaf83a99f/href">https://medium.com/media/35256ab3079573613eac2c8eaf83a99f/href</a></iframe><p><strong>Problem</strong> : In above code snippet , we are passing <strong>fn function </strong>as the argument to useFunctionHook. The <strong>fn</strong> reference changes on every render of component App. It can cause the effect to re-run again even when it is not desired. Let’s give our first try to fix this issue.</p><p><strong>CASE 1 TRY 1:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7687502bebf27df37165e147d5fd2cbb/href">https://medium.com/media/7687502bebf27df37165e147d5fd2cbb/href</a></iframe><p>Above we moved out the fn definition and now, it will have same reference across re-render. But it’s not always possible to do. We most of the times need access to the local variables available in Components and custom hooks. Following the approach above , will make it difficult to do so.</p><p><strong>CASE 1 TRY 2:</strong></p><p>React also gives us a special hook named as useCallback, which allows us to keep the reference intact based on dependency list passed as the second argument. Here is the API for useCallback</p><pre>const fn = useCallback(function() {}, [a, b, c])</pre><p>The first argument function is synchronised with the elements in dependency lists. The fn will only point to a new reference when a, b or c changes in this example. Let’s make use of it to solve our problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3088622cc02c614acc7db4d5d5ea2b1f/href">https://medium.com/media/3088622cc02c614acc7db4d5d5ea2b1f/href</a></iframe><p>In the example above, now the fn is again part of the component, but now fn has the access to all the variables inside component due to closures. And also the useFunctionHook makes use of useCallback to persist the reference of fn. In the example the reference of fn will not change across re-render.</p><p>Now lets say the fn access some value from the component something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bab7cc5007276fa17a6a282d0b327d9/href">https://medium.com/media/9bab7cc5007276fa17a6a282d0b327d9/href</a></iframe><p>But the the fn reference will not change across re-render as the dependency is blank array in our case.</p><pre>const fnCallback = React.useCallback(fn, [])</pre><p>So in our case , The count referenced by function fn will refer to same initial value across re-render.</p><p><strong>The closures created once will persist across re-renders unless the <br>callback runs again.</strong></p><p>Fix is easy, now add count as the dependency for useCallback. For that we must pass countInparent also now to useFunctionHook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/785945b3abb756a6cb73a17c5d8cae51/href">https://medium.com/media/785945b3abb756a6cb73a17c5d8cae51/href</a></iframe><p>One more alternate adjustment we could have done here is instead of having memoized the callback in useFunctionHook, we could have done it in App component.</p><p>But I think that’s not a good way to go ahead. It’s better if consumer of a custom hook has to do less things to make it work. In our case , we pulled the burden for maintaining the reference to function fn from App component. I think that’s good developer experience.</p><p>On the same lines, some may say useRef is also a viable option here. I would say the typical answer which is it depends. So let’s try the solutions with useRef.</p><p><strong>CASE 1 TRY 3 :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/968ed5a96fd5ef62cf675b07ffbd8acd/href">https://medium.com/media/968ed5a96fd5ef62cf675b07ffbd8acd/href</a></iframe><p>This approach also work for various scenarios. But there are few things to keep in mind before choosing useRef.</p><ol><li>Unlike useCallback there is no separate dependencies like array, so what could have been achieved with single line may require multiple lines with useRef. we can also write a custom hook like this, which removes some of verbosity from the above code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21997bbbf53192f2c10ffe14f355bc16/href">https://medium.com/media/21997bbbf53192f2c10ffe14f355bc16/href</a></iframe><p>Now the above example can be written as :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a0bd3aafb93ca9c48947f2b3e6cb0f1/href">https://medium.com/media/2a0bd3aafb93ca9c48947f2b3e6cb0f1/href</a></iframe><p>The ref approach becomes silent dependencies. What do I mean by silent dependencies ? . Let’s see that</p><pre>useEffect(() =&gt; {<br>  // some logic<br>}, [refDependency, nonRefDependency1, nonRefDependency2])</pre><p>Here above , refDependency will never change after first run. But the values refDependency might be carrying will be updated on every run .</p><pre>const { current: updatedValueAlways } = refDependency<br>//The value updates always but not the ref(refDependency) reference</pre><p>But nonRefDependency1 and nonRefDependency2 are non ref dependency which will change when their respective value changes on re-render. <br>At times, it becomes impossible to trigger rerun of the effect callback on value change. <br>So if only refDependency.current changes , it will not trigger the effect callback to run because refDependency itself has not changed.</p><p>Before, we move ahead let’s see one of the pattern that can used for avoiding the more work from consumers of custom hooks.</p><p><strong>CASE 2</strong><br>Let’s call it <strong>ref callback pattern</strong> for now(So this name is pretty common, that I have heard recently, but sounds legit). Now let’s observe the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/514068f7e916dd3fa0eb688d5150b237/href">https://medium.com/media/514068f7e916dd3fa0eb688d5150b237/href</a></iframe><p><strong>PROBLEM:</strong> In the code above , the App holds the responsibility of passing ref to useFunctionHook. But again as discussed above, we should avoid the effort from the consumer of the hook as much as possible. I think same concept applies for almost every thing in programming. So let’s try to do so.</p><p><strong>CASE 2 TRY 1</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dde6a2db368386474e6048a5bfe8d31f/href">https://medium.com/media/dde6a2db368386474e6048a5bfe8d31f/href</a></iframe><p>Notice above , how we are using the our callback way of setting up ref. We have also pulled out the responsibility of creating ref from the App component. <br>Now consumers do not need to worry about creating a ref every time to consume the hook. It would be good if we can extract the functionality of creating callback refs in a common hook. Let’s do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bd7e69ac167ff8801abc51605b27590/href">https://medium.com/media/1bd7e69ac167ff8801abc51605b27590/href</a></iframe><p>Now the code changes to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/841e347c926513d1ead2a0a962aa7614/href">https://medium.com/media/841e347c926513d1ead2a0a962aa7614/href</a></iframe><p>To summarise the ways we can handle callbacks with react hooks are:</p><p><strong>1.</strong> If possible move out the callback outside the component. This will not be possible almost every time. So mind it.</p><p><strong>2. </strong>If the callback is not dependent on any of the values in component scope, then go for useCallback approach or useRef approach with blank dependencies.Remember they become silent in those cases. Can be tricky as the closure created once will not update itself unless it runs again.</p><p><strong>3.</strong> If the callback need to change when certain values changes, go for useCallback approach, passing in desired dependencies.</p><p><strong>4. </strong>Try to minimize the things that consumer of a hook or component have to do to get things working.</p><p>Now we talked about various ways of handling functions with custom hooks. Let’s understand how we are going to handle array and objects with custom hooks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a40d9326031eaa99373fdbceed24bba/href">https://medium.com/media/6a40d9326031eaa99373fdbceed24bba/href</a></iframe><p>Notice Type 1 and Type 2 versions of useAcceptOptions hook. Doing the Type 1 will make the the debugging difficult. But the Type 2 can be more deterministic and debugging can be easy. For arrays and objects, nothing has changed. Try to avoid putting dependency like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ada062126987be63fd14caa4233f7814/href">https://medium.com/media/ada062126987be63fd14caa4233f7814/href</a></iframe><p>It’s very common to pass the options inline , so writing like above will run the callback of effect hook to run every time. Try to keep the options as small set of values. Having big objects and array argument to custom hooks becomes difficult to reason later.<br>Let’s see one more example having functions, object and arrays in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c184f67ac0ce39b0a685b45302bc746/href">https://medium.com/media/8c184f67ac0ce39b0a685b45302bc746/href</a></iframe><p>In the example we are just using the knowledge which we have discussed in this article till now. I am not going to explain the code above. I think you should go ahead and read it.</p><p>I think mix of useCallback, useRefValues and useCallbackRef solves almost all of the issues.</p><p><strong>Update: How to take care of debounced actions with hooks.</strong></p><p>Let’s see the code sample below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d62f1e6a932388129ce5195ebb3fe9c4/href">https://medium.com/media/d62f1e6a932388129ce5195ebb3fe9c4/href</a></iframe><p>Now above case will work as expected. But what if <strong><em>makeApiCallRaw </em></strong>is dependent on some other value in ChildComponent scope. Then it might not work because every render will create a new instance of debounced function.</p><p>Let’s see the behaviour in that case.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fstack26%2Fembed%2Fpreview%2FoNgowOj%3Fheight%3D600%26slug-hash%3DoNgowOj%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fstack26%2Fpen%2FoNgowOj&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3af7cb48b4bff52e010f7dc4afe4ffd5/href">https://medium.com/media/3af7cb48b4bff52e010f7dc4afe4ffd5/href</a></iframe><p>Observe the logs!!. Notice how the debounced action is not working as expected. Let’s make some changes to fix it</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fstack26%2Fembed%2Fpreview%2FJjorQVd%3Fheight%3D600%26slug-hash%3DJjorQVd%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fstack26%2Fpen%2FJjorQVd&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F379080.JjorQVd.small.816224dd-695f-4bf5-9efe-f04aa17a440e.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b341957f59b53217689539835ec6a2/href">https://medium.com/media/96b341957f59b53217689539835ec6a2/href</a></iframe><p>Notice now the debounced function is running as expected. But what we changed.</p><ol><li>We moved the value from dependency to argument for <strong><em>makeApiCallRaw. </em></strong>And now the reference to <strong><em>makeApiCall</em></strong> will not change across rerender and debounce will work as expected.</li><li>I have noticed this behaviour , more with controlled components. When the onChange should trigger non debounced and debounced changes at the same time.</li></ol><p>Feel free to point if any issues with the code snippets above. I have also written a handy library to debug hooks. Feel free to try it and let me know. A babel plugin is also available for it.</p><ul><li><a href="https://www.npmjs.com/package/@simbathesailor/use-what-changed">@simbathesailor/use-what-changed</a></li><li><a href="https://twitter.com/simbatheesailor"></a></li></ul><p>As told above, these are my experiences while writing hooks for since last year. Please let me know if there are any other good patterns that you guys have been using.</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67a984d42f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>