<?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 Joseph Chamochumbi on Medium]]></title>
        <description><![CDATA[Stories by Joseph Chamochumbi on Medium]]></description>
        <link>https://medium.com/@icjoseph?source=rss-4e80af6abc1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zHPGTDTsYFX68CCS5CkZOg.jpeg</url>
            <title>Stories by Joseph Chamochumbi on Medium</title>
            <link>https://medium.com/@icjoseph?source=rss-4e80af6abc1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:03:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@icjoseph/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[The for-of loop complaint]]></title>
            <link>https://medium.com/@icjoseph/the-for-of-loop-complaint-46c50be0e28c?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/46c50be0e28c</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 16:21:39 GMT</pubDate>
            <atom:updated>2023-03-10T09:01:46.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>For-of versus find</h3><figure><img alt="Loops, they always continue." src="https://cdn-images-1.medium.com/max/1024/0*FednQVIwqvtwf0X7" /><figcaption>Photo by <a href="https://unsplash.com/@kierinsight?utm_source=medium&amp;utm_medium=referral">Kier... in Sight</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here comes a short one.</p><p>If you are using AirBnb’s linting rules, you’ve probably seen this message:</p><pre>iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them</pre><p>This could easily happen if you loop over a list using for-of syntax.</p><p>At first I though, that this would be a situation where silencing the linter could be acceptable. However, it is probably best to avoid this kind of syntax and listen to the linter.</p><p>Take for example a situation where you’d want to loop over a list, but effectively stop when you hit a given value.</p><pre>const main = () =&gt; {<br>  for (const val of [0, 1, 2, 3, 4, 5]) {<br>    if (val % 4 === 0) {<br>      return val;<br>    }<br>  }<br><br>  return 0;<br>};<br><br>main();</pre><p>If you think of array methods, such as map, filter, reduce, forEach, which are often the usual suspects used to replace for loops, then the idea of stopping at any given point of the iteration might seem impossible.</p><p>You might also think of a trick to stop the reduce, by checking if a previous value is what we wanted, and from there just keep on returning it, but we’d still need to traverse the rest of the list, doing nothing!</p><p>There’s a group of methods which can stop at any given point of the iteration, <strong>some </strong>, <strong>every</strong> ,<strong> </strong><strong>find</strong> , <strong>findIndex</strong> ,<strong> </strong>indexOf. These have the property that when their predicate is “truthy” (caveat on indexOf ), then they stop and return the given value.</p><pre>const main = () =&gt; {<br>  return [0, 1, 2, 3, 4, 5].find((val) =&gt; val % 4 === 0) || 0;<br>};<br><br>main();</pre><p>These are from left-to-right operations, and nowadays you can find right-to-left versions, aptly suffixed with last, namely findLast and findLastIndex.</p><blockquote>Naturally, if you know your JavaScript this was straight up obvious to you, however, some of us might be <a href="https://github.com/airbnb/javascript/issues/1271">distracted by the lint complaint, and seek answers</a>!</blockquote><p>Anyway, back to for-of loops and the linting complaint. It’s not just that the code using find is shorter, but it turns out that the bytecode generated by the for-of loop is actually larger.</p><p>The find option uses 3 registers and has a bytecode length of 24. The for-of option uses 13 registers and has a bytecode length of 151.</p><p>It doesn’t necessarily mean that it is less optimal, but it does require more registers, and a bunch of checks to see if there are more items in the iterator, or if its time to exit and continue with the rest of the code.</p><p>And that’s the key issue, our loop has been wrapped by iterable-protocol checks.</p><pre>const main = () =&gt; {<br>  const arr = [0, 1, 2, 3, 4, 5];<br><br>  for (let index = 0; index &lt; arr.length; index++) {<br>    if (arr[index] % 4 === 0) {<br>      return arr[index];<br>    }<br>  }<br><br>  return 0;<br>};<br><br>main();</pre><p>Replacing the for-of loop with a good ol’ loop, removes the iterable-protocol checks, and reduces the bytecode significantly, although, not as much as the find code.</p><p>This good ol’ loop uses 3 registers and has a bytecode length of 47.</p><p>To produce these results, I used node — print-bytecode — print-bytecode-filter=functionname filename with Node 16.14.x.</p><p>Does this fully explain, or justify the lint complaint? Hardly. The key take away for me is that the for-of loop, does indeed require more work, when compared to the find alternative, or even the good ol’ for loop.</p><p>So there you have it, in this situation find seems like a more reasonable option, if anything because it produces less byte code.</p><p>For completeness sake,<a href="https://jsbench.me/vslcevy5wp/1"> I ran a benchmark</a> between all 3 alternatives shown here. The simple forloop was fastest, find was second place, and it was about 1% slower. Using for-of was about 5% slower than the for loop.</p><p>This article explores this matter further: <a href="https://gist.github.com/ljharb/58faf1cfcb4e6808f74aae4ef7944cff">Array Iteration</a>, and was my source for this piece.</p><p>Long ago I wrote on dev.to about <a href="https://dev.to/icyjoseph/filtering-in-typescript-2mbc">filtering in Typescript</a>, using type guards. You might want to review that article as complementary content.</p><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46c50be0e28c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component Composition, state and data fetching hooks]]></title>
            <link>https://medium.com/@icjoseph/react-component-composition-state-and-data-fetching-hooks-fd476dda5c30?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd476dda5c30</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Mon, 17 Jan 2022 13:26:42 GMT</pubDate>
            <atom:updated>2022-01-18T14:04:52.328Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>This is an expanded version of an answer I gave on the </em><a href="https://github.com/vercel/swr/discussions/1782"><em>swr discussions page</em></a><em>.</em></blockquote><figure><img alt="My working from home setup for 2021" src="https://cdn-images-1.medium.com/max/1024/1*TxLCHLAwXoqEnYHi9UegqA.jpeg" /></figure><p>React Component Composition is an often misunderstood and underused pattern. I have the impression that we often rather use React Context, or the pattern of using smart and dumb components, over Component Composition.</p><blockquote><em>One of the best ways to avoid prop-drilling is to use React component composition.</em></blockquote><p>At its heart, this kind of composition, is a way to sprinkle data into an structure. It usually takes advantage of the React <strong>children</strong> prop, and it looks like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520Header%252520%25253D%252520%2528%25257B%252520children%252520%25257D%2529%252520%25253D%25253E%252520%25253Cheader%25253E%25257Bchildren%25257D%25253C%25252Fheader%25253E%25253B%25250A%25250Aconst%252520Content%252520%25253D%252520%2528%25257B%252520children%252520%25257D%2529%252520%25253D%25253E%252520%25253Cdiv%25253E%25257Bchildren%25257D%25253C%25252Fdiv%25253E%25253B%25250A%25250Aconst%252520List%252520%25253D%252520%2528%25257B%252520children%252520%25257D%2529%252520%25253D%25253E%252520%25253Cul%25253E%25257Bchildren%25257D%25253C%25252Ful%25253E%25253B%25250A%25250Aconst%252520DashBoard%252520%25253D%252520%2528%25257B%252520user%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%25253Csection%25253E%25250A%252520%252520%252520%252520%25253CHeader%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Ch1%25253EWelcome%252520%25257Buser.name%25257D%25253C%25252Fh1%25253E%25250A%252520%252520%252520%252520%25253C%25252FHeader%25253E%25250A%25250A%252520%252520%252520%252520%25253CContent%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cp%25253EThese%252520are%252520you%252520favorite%252520%25257Buser.items.type%25257D%25253C%25252Fp%25253E%25250A%25250A%252520%252520%252520%252520%252520%252520%25253CList%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25257Buser.items.collection.map%2528%2528%25257B%252520uuid%25252C%252520label%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%25253Cli%252520key%25253D%25257Buuid%25257D%25253E%25257Blabel%25257D%25253C%25252Fli%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%2529%2529%25257D%25250A%252520%252520%252520%252520%252520%252520%25253C%25252FList%25253E%25250A%252520%252520%252520%252520%25253C%25252FContent%25253E%25250A%252520%252520%25253C%25252Fsection%25253E%25250A%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520Header%25252520%2525253D%25252520%252528%2525257B%25252520children%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%2525253Cheader%2525253E%2525257Bchildren%2525257D%2525253C%2525252Fheader%2525253E%2525253B%2525250A%2525250Aconst%25252520Content%25252520%2525253D%25252520%252528%2525257B%25252520children%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%2525253Cdiv%2525253E%2525257Bchildren%2525257D%2525253C%2525252Fdiv%2525253E%2525253B%2525250A%2525250Aconst%25252520List%25252520%2525253D%25252520%252528%2525257B%25252520children%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%2525253Cul%2525253E%2525257Bchildren%2525257D%2525253C%2525252Ful%2525253E%2525253B%2525250A%2525250Aconst%25252520DashBoard%25252520%2525253D%25252520%252528%2525257B%25252520user%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%2525253Csection%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253CHeader%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Ch1%2525253EWelcome%25252520%2525257Buser.name%2525257D%2525253C%2525252Fh1%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252FHeader%2525253E%2525250A%2525250A%25252520%25252520%25252520%25252520%2525253CContent%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cp%2525253EThese%25252520are%25252520you%25252520favorite%25252520%2525257Buser.items.type%2525257D%2525253C%2525252Fp%2525253E%2525250A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CList%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257Buser.items.collection.map%252528%252528%2525257B%25252520uuid%2525252C%25252520label%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cli%25252520key%2525253D%2525257Buuid%2525257D%2525253E%2525257Blabel%2525257D%2525253C%2525252Fli%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%252529%252529%2525257D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252FList%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252FContent%2525253E%2525250A%25252520%25252520%2525253C%2525252Fsection%2525253E%2525250A%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/31deaf3952bb1311b61d4930f3ac512c/href">https://medium.com/media/31deaf3952bb1311b61d4930f3ac512c/href</a></iframe><p>As opposed to using “prop-drilling” to do something like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520Header%252520%25253D%252520%2528%25257B%252520name%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%25253Cheader%25253E%25250A%252520%252520%252520%252520%25253Ch1%25253EWelcome%252520%25257Bname%25257D%25253C%25252Fh1%25253E%25250A%252520%252520%25253C%25252Fheader%25253E%25250A%2529%25253B%25250A%25250Aconst%252520Content%252520%25253D%252520%2528%25257B%252520type%25252C%252520collection%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%25253Cdiv%25253E%25250A%252520%252520%252520%252520%25253Cp%25253EThese%252520are%252520you%252520favorite%252520%25257Btype%25257D%25253C%25252Fp%25253E%25250A%252520%252520%252520%252520%25253CList%252520listItems%25253D%25257Bcollection%25257D%252520%25252F%25253E%25250A%252520%252520%25253C%25252Fdiv%25253E%25250A%2529%25253B%25250A%25250Aconst%252520List%252520%25253D%252520%2528%25257B%252520listItems%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%25253Cul%25253E%25250A%252520%252520%252520%252520%25257BlistItems.map%2528%2528%25257B%252520uuid%25252C%252520label%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%252520%252520%252520%252520%25253Cli%252520key%25253D%25257Buuid%25257D%25253E%25257Blabel%25257D%25253C%25252Fli%25253E%25250A%252520%252520%252520%252520%2529%2529%25257D%25250A%252520%252520%25253C%25252Ful%25253E%25250A%2529%25253B%25250A%25250Aconst%252520DashBoard%252520%25253D%252520%2528%25257B%252520user%252520%25257D%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%25253Csection%25253E%25250A%252520%252520%252520%252520%25253CHeader%252520name%25253D%25257Buser.name%25257D%252520%25252F%25253E%25250A%252520%252520%252520%252520%25253CContent%252520%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520type%25253D%25257Buser.items.type%25257D%252520%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520collections%25253D%25257Buser.items.collection%25257D%252520%25250A%252520%252520%252520%252520%252520%25252F%25253E%25250A%252520%252520%25253C%25252Fsection%25253E%25250A%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520Header%25252520%2525253D%25252520%252528%2525257B%25252520name%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%2525253Cheader%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253Ch1%2525253EWelcome%25252520%2525257Bname%2525257D%2525253C%2525252Fh1%2525253E%2525250A%25252520%25252520%2525253C%2525252Fheader%2525253E%2525250A%252529%2525253B%2525250A%2525250Aconst%25252520Content%25252520%2525253D%25252520%252528%2525257B%25252520type%2525252C%25252520collection%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%2525253Cdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253Cp%2525253EThese%25252520are%25252520you%25252520favorite%25252520%2525257Btype%2525257D%2525253C%2525252Fp%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253CList%25252520listItems%2525253D%2525257Bcollection%2525257D%25252520%2525252F%2525253E%2525250A%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%252529%2525253B%2525250A%2525250Aconst%25252520List%25252520%2525253D%25252520%252528%2525257B%25252520listItems%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%2525253Cul%2525253E%2525250A%25252520%25252520%25252520%25252520%2525257BlistItems.map%252528%252528%2525257B%25252520uuid%2525252C%25252520label%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cli%25252520key%2525253D%2525257Buuid%2525257D%2525253E%2525257Blabel%2525257D%2525253C%2525252Fli%2525253E%2525250A%25252520%25252520%25252520%25252520%252529%252529%2525257D%2525250A%25252520%25252520%2525253C%2525252Ful%2525253E%2525250A%252529%2525253B%2525250A%2525250Aconst%25252520DashBoard%25252520%2525253D%25252520%252528%2525257B%25252520user%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%2525253Csection%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253CHeader%25252520name%2525253D%2525257Buser.name%2525257D%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253CContent%25252520%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520type%2525253D%2525257Buser.items.type%2525257D%25252520%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520collections%2525253D%2525257Buser.items.collection%2525257D%25252520%2525250A%25252520%25252520%25252520%25252520%25252520%2525252F%2525253E%2525250A%25252520%25252520%2525253C%2525252Fsection%2525253E%2525250A%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9cf67a330df80cbc8fbb8fb25aaee31/href">https://medium.com/media/d9cf67a330df80cbc8fbb8fb25aaee31/href</a></iframe><p>As usual the <a href="https://reactjs.org/docs/composition-vs-inheritance.html">React docs</a> explain it very well. However, the goal of this article is not to explain how React Component Composition works, you can watch <a href="https://www.youtube.com/watch?v=3XaXKiXtNjw">this video by Michael Jackson</a> who does one of the best explanations I’ve seen.</p><h3>State and React Component Composition</h3><p>Now that we agree on what’s React Component Composition, let’s look at what happens when we combine this pattern with state.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520List%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520console.count%2528%252522List%252522%2529%25250A%25250A%252520%252520return%252520%2528%25250A%252520%252520%252520%252520%25253Cul%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cli%25253E1%25253C%25252Fli%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cli%25253E2%25253C%25252Fli%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cli%25253E3%25253C%25252Fli%25253E%25250A%252520%252520%252520%252520%25253C%25252Ful%25253E%25250A%252520%252520%2529%25253B%25250A%25257D%25253B%25250A%25250Afunction%252520Counter%2528%25257B%252520children%252520%25257D%2529%252520%25257B%25250A%252520%252520const%252520%25255Bcount%25252C%252520setCount%25255D%252520%25253D%252520useState%25280%2529%25253B%25250A%25250A%252520%252520useEffect%2528%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520%252520%252520const%252520timeout%252520%25253D%252520setTimeout%2528setCount%25252C%2525201000%25252C%252520count%252520%25252B%2525201%2529%25253B%25250A%252520%252520%252520%252520%252520%252520return%252520%2528%2529%252520%25253D%25253E%252520clearTimeout%2528timeout%2529%25250A%252520%252520%25257D%25252C%252520%25255Bcount%25255D%2529%25250A%252520%252520%25250A%252520%252520return%252520%2528%25250A%252520%252520%252520%252520%25253Cdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cp%25253E%25257Bcount%25257D%25253C%25252Fp%25253E%25250A%252520%252520%252520%252520%25250A%252520%252520%252520%252520%252520%252520%25257Bchildren%25257D%25250A%252520%252520%252520%252520%25253C%25252Fdiv%25253E%25250A%252520%252520%2529%25253B%25250A%25257D%25250A%25250Aconst%252520Dashboard%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520%2528%25250A%252520%252520%25253CCounter%25253E%25250A%252520%252520%252520%252520%25253CList%252520%25252F%25253E%25250A%252520%252520%25253C%25252FCounter%25253E%25250A%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520List%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520console.count%252528%25252522List%25252522%252529%2525250A%2525250A%25252520%25252520return%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253Cul%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cli%2525253E1%2525253C%2525252Fli%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cli%2525253E2%2525253C%2525252Fli%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cli%2525253E3%2525253C%2525252Fli%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252Ful%2525253E%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D%2525253B%2525250A%2525250Afunction%25252520Counter%252528%2525257B%25252520children%25252520%2525257D%252529%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525255Bcount%2525252C%25252520setCount%2525255D%25252520%2525253D%25252520useState%2525280%252529%2525253B%2525250A%2525250A%25252520%25252520useEffect%252528%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520const%25252520timeout%25252520%2525253D%25252520setTimeout%252528setCount%2525252C%252525201000%2525252C%25252520count%25252520%2525252B%252525201%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520return%25252520%252528%252529%25252520%2525253D%2525253E%25252520clearTimeout%252528timeout%252529%2525250A%25252520%25252520%2525257D%2525252C%25252520%2525255Bcount%2525255D%252529%2525250A%25252520%25252520%2525250A%25252520%25252520return%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cp%2525253E%2525257Bcount%2525257D%2525253C%2525252Fp%2525253E%2525250A%25252520%25252520%25252520%25252520%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257Bchildren%2525257D%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D%2525250A%2525250Aconst%25252520Dashboard%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520%252528%2525250A%25252520%25252520%2525253CCounter%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253CList%25252520%2525252F%2525253E%2525250A%25252520%25252520%2525253C%2525252FCounter%2525253E%2525250A%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/11e7ed6ec81972f7dafd0a9901d9f740/href">https://medium.com/media/11e7ed6ec81972f7dafd0a9901d9f740/href</a></iframe><p>With the above setup, over any period of time, <strong>List</strong> is rendered only once.</p><p>You may be surprised, because, there’s a 1000 milliseconds timeout on <strong>Counter</strong> that updates its <strong>count</strong> state, which as you know, triggers a render.</p><p>The reason why <strong>List</strong> renders once, is because, when the <strong>count</strong> state changes, <strong>children</strong> has not changed. Let&#39;s challenge this by changing the <strong>Counter</strong> to:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dfunction%252520Counter%2528%2529%252520%25257B%25250A%252520%252520const%252520%25255Bcount%25252C%252520setCount%25255D%252520%25253D%252520useState%25280%2529%25253B%25250A%25250A%252520%252520useEffect%2528%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520%252520%252520const%252520timeout%252520%25253D%252520setTimeout%2528setCount%25252C%2525201000%25252C%252520count%252520%25252B%2525201%2529%25253B%25250A%252520%252520%252520%252520%252520%252520return%252520%2528%2529%252520%25253D%25253E%252520clearTimeout%2528timeout%2529%25250A%252520%252520%25257D%25252C%252520%25255Bcount%25255D%2529%25250A%252520%252520%25250A%252520%252520return%252520%2528%25250A%252520%252520%252520%252520%25253Cdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cp%25253E%25257Bcount%25257D%25253C%25252Fp%25253E%25250A%252520%252520%252520%252520%25250A%252520%252520%252520%252520%252520%252520%25253CList%252520%25252F%25253E%25250A%252520%252520%252520%252520%25253C%25252Fdiv%25253E%25250A%252520%252520%2529%25253B%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dfunction%25252520Counter%252528%252529%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525255Bcount%2525252C%25252520setCount%2525255D%25252520%2525253D%25252520useState%2525280%252529%2525253B%2525250A%2525250A%25252520%25252520useEffect%252528%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520const%25252520timeout%25252520%2525253D%25252520setTimeout%252528setCount%2525252C%252525201000%2525252C%25252520count%25252520%2525252B%252525201%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520return%25252520%252528%252529%25252520%2525253D%2525253E%25252520clearTimeout%252528timeout%252529%2525250A%25252520%25252520%2525257D%2525252C%25252520%2525255Bcount%2525255D%252529%2525250A%25252520%25252520%2525250A%25252520%25252520return%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cp%2525253E%2525257Bcount%2525257D%2525253C%2525252Fp%2525253E%2525250A%25252520%25252520%25252520%25252520%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CList%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f183b96c358cac97e9925de22e612ab5/href">https://medium.com/media/f183b96c358cac97e9925de22e612ab5/href</a></iframe><p>We are now, invoking <strong>List</strong> inside <strong>Counter</strong>, so when the <strong>count</strong> state changes, React sees a new child, and renders it again.</p><blockquote><em>With this setup, in both cases, </em><strong><em>List</em></strong><em> is mounted only once! But in the second scenario it re-renders approximately every 1000 milliseconds.</em></blockquote><p>So, using React component composition, we can be cut down on the number of rendering needed. This doesn’t apply to every use case of course.</p><h3>Data fetching hooks</h3><p>Today data fetching hooks are very popular. Two I’ve used quite a bit are <strong>swr</strong> and <strong>react-query</strong>.</p><p>When using these libraries, we should always remember that when many hooks read the same cache key, they are in fact using the same data reference.</p><p>For example, if the cached value was a list, and you called <strong>sort</strong> directly on it, you&#39;ll mutate every other usage of this cached value, leading to interesting bugs.</p><p>These data fetching hooks, give you the ability to refresh the cached data automatically. For example, if the user returns to the tab containing your application, a request is started to refresh your data. These hooks can also do this at certain time intervals, or in response to mount, etc.</p><p>In the case of <strong>swr</strong>, a deep comparison check is performed, and it if the data has the same shape and values, then <strong>swr</strong> skips triggering a render, because the data was exactly the same.</p><p>With data fetching hooks, we can define a piece of data as a custom hook:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520fetcher%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520new%252520Promise%2528%2528resolve%2529%252520%25253D%25253E%252520setTimeout%2528resolve%25252C%252520500%25252C%252520%2527data%2527%2529%2529%25253B%25250A%25250Aconst%252520useData%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520return%252520useSWR%2528%2527key%2527%25252C%252520fetcher%2529%25253B%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520fetcher%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520new%25252520Promise%252528%252528resolve%252529%25252520%2525253D%2525253E%25252520setTimeout%252528resolve%2525252C%25252520500%2525252C%25252520%252527data%252527%252529%252529%2525253B%2525250A%2525250Aconst%25252520useData%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520return%25252520useSWR%252528%252527key%252527%2525252C%25252520fetcher%252529%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/991b6f4e6df4d9509a0bd63685b618bd/href">https://medium.com/media/991b6f4e6df4d9509a0bd63685b618bd/href</a></iframe><p>And then have different types and, of course, instances of a component consuming the same data, but what happens when, both a parent and some of its children use the same data hook?</p><p>Are we penalized with extra renders? Let’s inspect this application.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520Parent%252520%25253D%252520%2528%25257B%252520children%252520%25257D%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520const%252520%25257B%252520data%252520%25257D%252520%25253D%252520useData%2528%2529%25253B%25250A%252520%252520console.count%2528%252522Parent%252522%2529%25253B%25250A%25250A%252520%252520return%252520%2528%25250A%252520%252520%252520%252520%25253Csection%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Ch1%25253EParent%252520%25257Bdata%25257D%25253C%25252Fh1%25253E%25250A%25250A%252520%252520%252520%252520%252520%252520%25257Bchildren%25257D%25250A%25250A%252520%252520%252520%252520%252520%252520%25253CChild%252520label%25253D%252522inner%252522%252520%25252F%25253E%25250A%252520%252520%252520%252520%25253C%25252Fsection%25253E%25250A%252520%252520%2529%25253B%25250A%25257D%25253B%25250A%25250Aconst%252520Child%252520%25253D%252520%2528%25257B%252520label%252520%25257D%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520const%252520%25257B%252520data%252520%25257D%252520%25253D%252520useData%2528%2529%25253B%25250A%252520%252520console.count%2528%252560Child%25253A%252520%252524%25257Blabel%25257D%252560%2529%25253B%25250A%25250A%252520%252520return%252520%25253Cp%25253E%25257Bdata%25257D%25253C%25252Fp%25253E%25253B%25250A%25257D%25253B%25250A%25250Aconst%252520Dashboard%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520return%252520%2528%25250A%252520%252520%252520%252520%25253Cdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CParent%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CChild%252520label%25253D%2525221%252522%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CChild%252520label%25253D%2525222%252522%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CChild%252520label%25253D%2525223%252522%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%25253C%25252FParent%25253E%25250A%252520%252520%252520%252520%25253C%25252Fdiv%25253E%25250A%252520%252520%2529%25253B%25250A%25257D%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520Parent%25252520%2525253D%25252520%252528%2525257B%25252520children%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525257B%25252520data%25252520%2525257D%25252520%2525253D%25252520useData%252528%252529%2525253B%2525250A%25252520%25252520console.count%252528%25252522Parent%25252522%252529%2525253B%2525250A%2525250A%25252520%25252520return%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253Csection%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Ch1%2525253EParent%25252520%2525257Bdata%2525257D%2525253C%2525252Fh1%2525253E%2525250A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257Bchildren%2525257D%2525250A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CChild%25252520label%2525253D%25252522inner%25252522%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252Fsection%2525253E%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D%2525253B%2525250A%2525250Aconst%25252520Child%25252520%2525253D%25252520%252528%2525257B%25252520label%25252520%2525257D%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525257B%25252520data%25252520%2525257D%25252520%2525253D%25252520useData%252528%252529%2525253B%2525250A%25252520%25252520console.count%252528%25252560Child%2525253A%25252520%25252524%2525257Blabel%2525257D%25252560%252529%2525253B%2525250A%2525250A%25252520%25252520return%25252520%2525253Cp%2525253E%2525257Bdata%2525257D%2525253C%2525252Fp%2525253E%2525253B%2525250A%2525257D%2525253B%2525250A%2525250Aconst%25252520Dashboard%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520return%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CParent%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CChild%25252520label%2525253D%252525221%25252522%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CChild%25252520label%2525253D%252525222%25252522%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CChild%25252520label%2525253D%252525223%25252522%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252FParent%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e14e35a1c11b16fc44fb2456985125/href">https://medium.com/media/74e14e35a1c11b16fc44fb2456985125/href</a></iframe><p>Without strict mode, this would log:</p><pre>Parent: 1<br>Child: 1: 1<br>Child: 2: 1<br>Child: 3: 1<br>Child: inner: 1<br>Child: 1: 2<br>Child: 2: 2<br>Child: 3: 2<br>Child: inner: 2<br>Parent: 2<br>Child: inner: 3</pre><p>Logs are nice, but we shouldn’t let them dictate our understanding. Instead, we can profile the application using the <strong>React Dev Tools,</strong> which is what you should do in your applications.</p><p>Using <strong>NextJS</strong>, the profiling tool from <strong>React Dev Tools</strong> would show about 7 frames:</p><ol><li>First, everything renders</li><li>A Next JS Development Tool component renders (safe to ignore)</li><li>Child 1 renders</li><li>Child 2 renders</li><li>Child 3 renders</li><li>Child inner renders</li><li>Parent and Child inner render</li></ol><p>This means that using React Component Composition, in this case, prevents unnecessary extra renders of children 1, 2 and 3.</p><blockquote>The parent component children 1, 2, and 3 render exactly twice, but the inner child to parent, renders 3 times.</blockquote><p>Remember that this is not only true for <strong>swr</strong>, but in general for any form of state management, and that this is because the children prop has not changed during the render pass, only the child called <strong>inner</strong> is a new object every time, even though React knows there’s an instance of it already mounted.</p><p>That last detail is important, because if we create a version of <strong>Child</strong> with <strong>React.memo</strong>, then we could use it in place of the inner <strong>Child</strong> in <strong>Parent</strong>, and then the 7th frame would only show <strong>Parent</strong> rendering.</p><h3>Closing thoughts</h3><p>React component composition is a pattern which can help you organize your components, and even prevent excessive rendering in some situations.</p><p>The so called, re-rendering is not necessarily that bad, it only means that React collects updates.</p><p>In front end development, the word render is heavily overloaded. As a React concept, it means to call the render method of a class component, or simply calling your functional component, to collect an object which describes how it should look like. It is not inherently a bad thing if this process happens a few times and gives the same result.</p><p>Data fetching hooks are optimized to prevent re-rendering of callers, so unless your application is slow, you probably don’t need to spend resources optimizing how you use these hooks.</p><p>When using data fetching hooks, we must remember that, most of the time, components sharing a data slice, are actually using the same data reference, and that’s why you should avoid mutating this data!</p><p>Happy Hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd476dda5c30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In React, should you use Classes or Functional Components]]></title>
            <link>https://medium.com/@icjoseph/in-react-should-you-use-classes-or-functional-components-1ca50dae3414?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca50dae3414</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Tue, 19 Oct 2021 15:19:58 GMT</pubDate>
            <atom:updated>2021-10-19T15:19:58.914Z</atom:updated>
            <content:encoded><![CDATA[<h4>It was never about classes, it was always about state and life cycles.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzhH-poqYKX2PonSFTqYEg.jpeg" /><figcaption>Never stop learning! —<a href="https://www.instagram.com/ic_joseph/"> ic_joseph</a></figcaption></figure><p>Lately I’ve been visiting the<a href="https://reddit.com/r/reactjs"> Reddit board</a> for React, a rather fun and interesting place. There, I’ve been able to help some people’s questions, and most importantly, learn a lot from the community over there.</p><p>One thing I notice, is that, every now and then someone asks whether or not to use functional components, or if its now acceptable to use functional components over classes.</p><p>If you watched the hooks introduction presentation, you know that the React team itself said that hooks should be your default choice moving forward. Unless, for example, you need to implement Error boundaries, or need to access a component instance through a ref, though, this can be done with useImperativeHandle.</p><p>The truth is that, classes, were just a means to an end, an implementation detail.</p><p>You might not know this, but initially, all React components were classes. Even those that did not hold state. It was rather recently, or ages ago in internet time, that stateless functional components were added.</p><h3>The time dimension</h3><p>I am a subscriber to the idea that React components are functions that take in props and return a user interface block, or as we call it JSX.</p><p>I loved that it looks mathematical and that such model, makes composition easier to understand, because you could take in props and start a chain of function calls, for as long as you wished, making sure that at the end you returned JSX.</p><blockquote>A mental model on how a framework works, is incredible helpful!</blockquote><blockquote>There’s something called, working memory, and it can become overloaded fairly quick. Having a great understanding of the framework helps you reduce the germane load on your working memory. Germane load, simply put, is how many thoughts you have to store on your head as you read the code.</blockquote><blockquote>If you have a mental model for a framework then you need to think less about the framework, and you can focus on understanding what the code is trying to achieve.</blockquote><blockquote>If you are curious about this, I can recommend <a href="https://www.manning.com/books/the-programmers-brain?gclid=CjwKCAjw2bmLBhBREiwAZ6ugo6IKRNVLopEVmght0OrdHHp_TpGbsPxhG_EOZnEvJ9KF0MFhRVcLyBoCZ6AQAvD_BwE">The Programmer’s Brain</a> by Felienne Hermans.</blockquote><blockquote>Given that it is so important, you should regularly challenge your understanding of a framework!</blockquote><p>When I told someone about this, before hooks, then they would ask about classes, and I’d say that classes hold the time dimension. The description of how the component should behave as the application clock ticks forward, as the user interacts with it, as data is fetched.</p><p>Because of that I liked to structure my components from top to bottom. First the constructor, then componentDidMount, then componentDidUpdate , then componentWillUnmount , and always end with render.</p><p>Why is any of this rambling important? Because a stateless functional component, does not care about time. It just renders whatever its implementation calculated from its props. The so called, preparation part (before the return statement), is pure, and so the JSX part (the return statement), is predictable.</p><p>And so classes are a escape hatch, a connection, a hook, into React’s timeline, so called, life cycles and state management. Inside a class component React lets you see into a component’s life cycle, and it allows you to carry along state associated to the component.</p><p>It is important to notice that these two, access to React’s life cycles, and the ability to manage state, are orthogonal. They are not mutually exclusive, nor do they strictly imply each other.</p><p>Often if you are using state then you’ll probably need to use the life cycle methods too (or not!), but you could have a component without state and just access to life cycles.</p><h3>Function calls with extra steps</h3><p>This idea of React letting you see the component life cycles, and manage state, is, obviously, not a property of classes, but of React’s internals.</p><p>However, a class is an object that you can keep track of easily. You know, a class instance. Beside closures, JavaScript doesn’t really offer much more than that, but if you know about classes, you know these are just objects. In JavaScript, everything is an object as they say.</p><p>We also know that you can easily generate an object from a function. What if we made function calls in such a way that calling them gave us a perfect snapshot of all the work to do in life cycles and how to manage state.</p><p>If we broaden the idea of a function that takes in props to return JSX, into a function that takes in props, and a known number of extra arguments which React gives us closure over, to return JSX, then we can start letting go of classes.</p><blockquote>An unknown number of extra arguments, would make your component unpredictable!</blockquote><p>Hooks such as useState and useReducer do precisely this. When it’s time to render your component, React calls the component with the props it receives, and you get a special kind of closure over the state managed by React. All of these are the inputs for the functional component.</p><p>The state can be updated using the setters you get from these hooks, which you place wherever its needed. After an update, your component is called again with props and results from hooks. <strong>This is, approximately, my mental model</strong>, and not necessarily what happens in the JavaScript engine.</p><h3>The M word</h3><p>Let’s now define a function to collect additional (non rendering) work to do when render happens. Such a function is giving you access to life cycles.</p><p>Introduce a strict case where this additional work should only happen if something specific happens, and the a generic case where this work should only happen once. That’s useEffect, let’s call this work effect.</p><p>When should these effects happen? Well, React’s priority is to commit to the DOM, as soon as possible, so they are executed after that, but just in case someone needs them done before the commit, let’s add useLayoutEffect.</p><blockquote>Browsing React.js Reddit’s board, I also notice that we use the word “render” interchangeably, for a very wide variety of concepts. Here render, means collecting JSX from a React component.</blockquote><p>I am of course, simplifying a lot, and forcing the new state of things into my mental models, but one thing remains true, <strong>you really don’t need class Components anymore</strong>. They’re not a bad thing, but in React terms, they were just a means to an end.</p><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca50dae3414" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using React to understand Abort Controllers]]></title>
            <link>https://medium.com/@icjoseph/using-react-to-understand-abort-controllers-eb10654485df?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb10654485df</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 10:01:15 GMT</pubDate>
            <atom:updated>2022-11-18T08:31:28.536Z</atom:updated>
            <content:encoded><![CDATA[<p>In case you didn’t know, browsers support an API called AbortController, which is typically used to cancel ongoing fetch requests. More info always available at <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">MDN</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNOg8HsLZv8EgyxMNaaz_g.png" /><figcaption>An example using React’s useEffect.</figcaption></figure><h3>Step by Step</h3><p>Normally you fetch data and when it resolves you set some state with the response. However, there’s two situations to consider:</p><ul><li>The component querying for this data in unmounted from the DOM.</li><li>The data is not relevant anymore.</li></ul><p>The latter can happen for example if you are fetching friends of a user Joe, but Joe has too many friends so the request is slow. Before the request for Joe‘s friends resolves, you decide you want to see Jane‘s friends instead, but she has fewer friends so her request goes way faster and you show her friends list almost immediately, but then Joe‘s request resolves and overrides the friends list. In this case you would have wanted to cancel the first request.</p><p>There’s many techniques to do this, for example, for unmounted components, use a ref on a DOM element, and check if ref.current is not null when the response comes back, or the less preferred way of having an &quot;is-mounted” ref flag.</p><p>For irrelevant data you could use a variable, which both your request and the effect cleanup have closure over, so when clean up happens you set this variable to a value, and inside your promise chain you check for this value.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Funruffled-leftpad-e5los&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Funruffled-leftpad-e5los&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fe5los%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/6b5c2ae25b7ae6ef2ea5cf8a423cfb6c/href">https://medium.com/media/6b5c2ae25b7ae6ef2ea5cf8a423cfb6c/href</a></iframe><p>And there’s the AbortController, which fits both cases. You’d use this in a React useEffect hook like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3DuseEffect%2528%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520controller%252520%25253D%252520new%252520AbortController%2528%2529%25253B%25250A%252520%252520%252520%252520const%252520signal%252520%25253D%252520controller.signal%25253B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%25250A%252520%252520%252520%252520fetch%2528%2527my-resource%2527%25252C%252520%25257B%252520signal%252520%25257D%2529%25250A%252520%252520%252509%252520%252520.then%2528res%252520%25253D%25253E%252520res.json%2528%2529%2529%25250A%252520%252520%252520%252520%252520%252520.then%2528res%252520%25253D%25253E%252520setResource%2528res%2529%2529%25250A%252520%252520%252520%252520%252520%252520.catch%2528console.log%2529%25253B%25250A%25250A%252520%252520%252520%252520return%252520%2528%2529%252520%25253D%25253E%252520controller.abort%2528%2529%25253B%25250A%252520%252520%25257D%25252C%252520%25255B%25255D%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3DuseEffect%252528%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520controller%25252520%2525253D%25252520new%25252520AbortController%252528%252529%2525253B%2525250A%25252520%25252520%25252520%25252520const%25252520signal%25252520%2525253D%25252520controller.signal%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525250A%25252520%25252520%25252520%25252520fetch%252528%252527my-resource%252527%2525252C%25252520%2525257B%25252520signal%25252520%2525257D%252529%2525250A%25252520%25252520%25252509%25252520%25252520.then%252528res%25252520%2525253D%2525253E%25252520res.json%252528%252529%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.then%252528res%25252520%2525253D%2525253E%25252520setResource%252528res%252529%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.catch%252528console.log%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520return%25252520%252528%252529%25252520%2525253D%2525253E%25252520controller.abort%252528%252529%2525253B%2525250A%25252520%25252520%2525257D%2525252C%25252520%2525255B%2525255D%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/137b17d23150173328ae93e272155f57/href">https://medium.com/media/137b17d23150173328ae93e272155f57/href</a></iframe><p>But how does the Abort Controller work exactly?</p><p>When the abort method on the controller is called, the fetch operation and every subsequent, then methods are discarded, and the catch method is executed.</p><p>If you are setting an error state inside your catch block, then you need to differentiate the situation in which the catch block is called.</p><blockquote>if there’s no catch the error is passed to the caller. In create-react-app development mode, the error will overlay your page.</blockquote><p>To do this, check if the controller.signal.aborted flag is set to true.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3DuseEffect%2528%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520controller%252520%25253D%252520new%252520AbortController%2528%2529%25253B%25250A%252520%252520%252520%252520const%252520signal%252520%25253D%252520controller.signal%25253B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%25250A%252520%252520%252520%252520fetch%2528%2527my-resource%2527%25252C%252520%25257B%252520signal%252520%25257D%2529%25250A%252520%252520%252509%252520%252520.then%2528res%252520%25253D%25253E%252520res.json%2528%2529%2529%25250A%252520%252520%252520%252520%252520%252520.then%2528res%252520%25253D%25253E%252520setResource%2528res%2529%2529%25250A%252520%252520%252520%252520%252520%252520.catch%2528e%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520console.log%2528signal.aborted%2529%25250A%252520%252520%252520%252520%252520%252520%252520%25257D%2529%25253B%25250A%25250A%252520%252520%252520%252520return%252520%2528%2529%252520%25253D%25253E%252520controller.abort%2528%2529%25253B%25250A%252520%252520%25257D%25252C%252520%25255B%25255D%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3DuseEffect%252528%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520controller%25252520%2525253D%25252520new%25252520AbortController%252528%252529%2525253B%2525250A%25252520%25252520%25252520%25252520const%25252520signal%25252520%2525253D%25252520controller.signal%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525250A%25252520%25252520%25252520%25252520fetch%252528%252527my-resource%252527%2525252C%25252520%2525257B%25252520signal%25252520%2525257D%252529%2525250A%25252520%25252520%25252509%25252520%25252520.then%252528res%25252520%2525253D%2525253E%25252520res.json%252528%252529%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.then%252528res%25252520%2525253D%2525253E%25252520setResource%252528res%252529%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.catch%252528e%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520console.log%252528signal.aborted%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520return%25252520%252528%252529%25252520%2525253D%2525253E%25252520controller.abort%252528%252529%2525253B%2525250A%25252520%25252520%2525257D%2525252C%25252520%2525255B%2525255D%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/47c11e4109724b72d9a7b9e799047e7b/href">https://medium.com/media/47c11e4109724b72d9a7b9e799047e7b/href</a></iframe><p>If the controller.signal.aborted flag is true, then you can skip updating your error state.</p><blockquote>If you are into implicit calls and functional programming, or just plain understand JavaScript better than most, you could think of having: return controller.abort and use the fact that React will do call for you, but that will trigger illegal invocation because of loss of function context.</blockquote><h3>Cancelling any Promise</h3><p>The ability to cancel a promise is somewhat desirable in JavaScript. There are multiple techniques to do it, but here I’ll make use of the Abort Controller, in order to reinforce its utility.</p><p>Say we have discovered a magical function to create unique values, not quite but almost, call it randomId:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520randomId%252520%25253D%252520%2528delay%252520%25253D%252520200%2529%252520%25253D%25253E%25250A%252520%252520new%252520Promise%2528%2528accept%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520id%252520%25253D%252520Date.now%2528%2529.toString%252836%2529%252520%25252B%252520Math.random%2528%2529.toString%252836%2529.substr%25282%2529%25253B%25250A%252520%252520%252520%252520setTimeout%2528accept%25252C%252520delay%25252C%252520id%2529%25253B%25250A%252520%252520%25257D%2529%25253B%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520randomId%25252520%2525253D%25252520%252528delay%25252520%2525253D%25252520200%252529%25252520%2525253D%2525253E%2525250A%25252520%25252520new%25252520Promise%252528%252528accept%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520id%25252520%2525253D%25252520Date.now%252528%252529.toString%25252836%252529%25252520%2525252B%25252520Math.random%252528%252529.toString%25252836%252529.substr%2525282%252529%2525253B%2525250A%25252520%25252520%25252520%25252520setTimeout%252528accept%2525252C%25252520delay%2525252C%25252520id%252529%2525253B%2525250A%25252520%25252520%2525257D%252529%2525253B%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f43e2ab334c5c4a5aa366d7fd3e81530/href">https://medium.com/media/f43e2ab334c5c4a5aa366d7fd3e81530/href</a></iframe><p>For argument sake, turn this otherwise synchronous work, into a promise. It reads that after 200 milliseconds, we resolve with an id which is the concatenation of the current instant and a random number.</p><p>Let’s use it in a React app, by wrapping it all nicely inside a Resource component:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520randomId%252520%25253D%252520%2528delay%252520%25253D%252520200%2529%252520%25253D%25253E%25250A%252520%252520new%252520Promise%2528%2528accept%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520id%252520%25253D%252520Date.now%2528%2529.toString%252836%2529%252520%25252B%252520Math.random%2528%2529.toString%252836%2529.substr%25282%2529%25253B%25250A%252520%252520%252520%252520setTimeout%2528accept%25252C%252520delay%25252C%252520id%2529%25253B%25250A%252520%252520%25257D%2529%25253B%25250A%25250Aconst%252520Resource%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520const%252520%25255Bresource%25252C%252520setResource%25255D%252520%25253D%252520useState%2528%2527%2527%2529%25253B%25250A%25250A%252520%252520useEffect%2528%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520randomId%2528%2529%25250A%252520%252520%252520%252520%252520%252520.then%2528%2528res%2529%252520%25253D%25253E%252520setResource%2528res%2529%2529%25250A%252520%252520%25257D%25252C%252520%25255B%25255D%2529%25253B%25250A%25250A%252520%252520return%252520%2528%25250A%252520%252520%252520%252520%25253Cdiv%25253E%25250A%252520%252520%252520%252520%252520%252520randomId%25253A%252520%25253Cp%25253E%25257Bresource%25257D%25253C%25252Fp%25253E%25250A%252520%252520%252520%252520%25253C%25252Fdiv%25253E%25250A%252520%252520%2529%25253B%25250A%25257D%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520randomId%25252520%2525253D%25252520%252528delay%25252520%2525253D%25252520200%252529%25252520%2525253D%2525253E%2525250A%25252520%25252520new%25252520Promise%252528%252528accept%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520id%25252520%2525253D%25252520Date.now%252528%252529.toString%25252836%252529%25252520%2525252B%25252520Math.random%252528%252529.toString%25252836%252529.substr%2525282%252529%2525253B%2525250A%25252520%25252520%25252520%25252520setTimeout%252528accept%2525252C%25252520delay%2525252C%25252520id%252529%2525253B%2525250A%25252520%25252520%2525257D%252529%2525253B%2525250A%2525250Aconst%25252520Resource%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525255Bresource%2525252C%25252520setResource%2525255D%25252520%2525253D%25252520useState%252528%252527%252527%252529%2525253B%2525250A%2525250A%25252520%25252520useEffect%252528%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520randomId%252528%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.then%252528%252528res%252529%25252520%2525253D%2525253E%25252520setResource%252528res%252529%252529%2525250A%25252520%25252520%2525257D%2525252C%25252520%2525255B%2525255D%252529%2525253B%2525250A%2525250A%25252520%25252520return%25252520%252528%2525250A%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520randomId%2525253A%25252520%2525253Cp%2525253E%2525257Bresource%2525257D%2525253C%2525252Fp%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffef4d12c6331d16a6b4f81695d25cf0/href">https://medium.com/media/ffef4d12c6331d16a6b4f81695d25cf0/href</a></iframe><p>And finally render it as part of a React app. I use an image here, because Medium doesn’t allow inline onClick events in Carbon embeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-UvtFkoDEN9xO-Er1fWVA.png" /><figcaption>App to render a random id, using Resource.</figcaption></figure><p>A few things to note:</p><ul><li>We toggle the Resource, which triggers an asynchronous process when mounted.</li><li>If there’s an ongoing asynchronous process and we toggle down the Resource component, then the asynchronous process resolves on an already unmounted component. This triggers a React warning.</li></ul><p>Let’s create a mechanism to cancel the process of getting the random, pseudo-unique id.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520randomId%252520%25253D%252520%2528signal%252520%25253D%252520null%25252C%252520delay%252520%25253D%2525203000%2529%252520%25253D%25253E%25250A%252520%252520new%252520Promise%2528%2528accept%25252C%252520cancel%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520id%252520%25253D%252520Date.now%2528%2529.toString%252836%2529%252520%25252B%252520Math.random%2528%2529.toString%252836%2529.substr%25282%2529%25253B%25250A%25250A%252520%252520%252520%252520const%252520timeout%252520%25253D%252520setTimeout%2528accept%25252C%252520delay%25252C%252520id%2529%25253B%25250A%25250A%252520%252520%252520%252520if%252520%2528signal%252520instanceof%252520AbortSignal%2529%252520%25257B%25250A%252520%252520%252520%252520%252520%252520signal.addEventListener%2528%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252522abort%252522%25252C%25250A%252520%252520%252520%252520%252520%252520%252520%252520%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520clearTimeout%2528timeout%2529%25253B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520cancel%2528%252522Cancelled%252522%2529%25253B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25257D%25252C%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25257B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520once%25253A%252520true%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25257D%25250A%252520%252520%252520%252520%252520%252520%2529%25253B%25250A%252520%252520%252520%252520%25257D%25250A%252520%252520%25257D%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520randomId%25252520%2525253D%25252520%252528signal%25252520%2525253D%25252520null%2525252C%25252520delay%25252520%2525253D%252525203000%252529%25252520%2525253D%2525253E%2525250A%25252520%25252520new%25252520Promise%252528%252528accept%2525252C%25252520cancel%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520id%25252520%2525253D%25252520Date.now%252528%252529.toString%25252836%252529%25252520%2525252B%25252520Math.random%252528%252529.toString%25252836%252529.substr%2525282%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520const%25252520timeout%25252520%2525253D%25252520setTimeout%252528accept%2525252C%25252520delay%2525252C%25252520id%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520if%25252520%252528signal%25252520instanceof%25252520AbortSignal%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520signal.addEventListener%252528%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252522abort%25252522%2525252C%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520clearTimeout%252528timeout%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520cancel%252528%25252522Cancelled%25252522%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%2525252C%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520once%2525253A%25252520true%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525250A%25252520%25252520%2525257D%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f4beee49a0fe11380799f75be4a6d03/href">https://medium.com/media/2f4beee49a0fe11380799f75be4a6d03/href</a></iframe><p>Pardon me for not using TypeScript for this one, but in this case signal is an Abort Signal type, which is also an object in the browser API.</p><p>This randomId function can now take an optional signal. If the signal is an instance of AbortSignal then we attach an event listener to it, which will clear the ongoing timeout, when an abort event happens.</p><p>This event listener shall be ran only once.</p><p>Then all that’s left to do is to use an AbortController in useEffect method inside Resource:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3D%252520%252520useEffect%2528%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520controller%252520%25253D%252520new%252520AbortController%2528%2529%25253B%25250A%25250A%252520%252520%252520%252520randomId%2528controller.signal%2529%25250A%252520%252520%252520%252520%252520%252520.then%2528%2528res%2529%252520%25253D%25253E%252520setResource%2528res%2529%2529%25250A%252520%252520%252520%252520%252520%252520.catch%2528%2528e%2529%252520%25253D%25253E%252520console.log%2528e%25252C%252520controller.signal.aborted%2529%2529%25253B%25250A%25250A%252520%252520%252520%252520return%252520%2528%2529%252520%25253D%25253E%252520controller.abort%2528%2529%25253B%25250A%252520%252520%25257D%25252C%252520%25255B%25255D%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3D%25252520%25252520useEffect%252528%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520controller%25252520%2525253D%25252520new%25252520AbortController%252528%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520randomId%252528controller.signal%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.then%252528%252528res%252529%25252520%2525253D%2525253E%25252520setResource%252528res%252529%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520.catch%252528%252528e%252529%25252520%2525253D%2525253E%25252520console.log%252528e%2525252C%25252520controller.signal.aborted%252529%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520return%25252520%252528%252529%25252520%2525253D%2525253E%25252520controller.abort%252528%252529%2525253B%2525250A%25252520%25252520%2525257D%2525252C%25252520%2525255B%2525255D%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6087507271e2b2803fa542f0aa158c7b/href">https://medium.com/media/6087507271e2b2803fa542f0aa158c7b/href</a></iframe><p>A link with the entire code can be found here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fancient-shape-q4im1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fancient-shape-q4im1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fq4im1%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/45f53e62fe3fe289c881a12593187a13/href">https://medium.com/media/45f53e62fe3fe289c881a12593187a13/href</a></iframe><p>What happened?</p><ul><li>When Resource unmounted, the clean up function in useEffect calls the abort method in the controller.</li><li>This triggers an abort event, which our signal is listening to.</li><li>This in turn triggers the cancellation of the timeout that resolves the id, and also rejects the promise.</li></ul><p>There’s one last thing, when the promise does resolve, we should detach the on abort event listener.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%252520randomId%252520%25253D%252520%2528signal%252520%25253D%252520null%25252C%252520delay%252520%25253D%2525203000%2529%252520%25253D%25253E%25250A%252520%252520new%252520Promise%2528%2528accept%25252C%252520cancel%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520const%252520id%252520%25253D%252520Date.now%2528%2529.toString%252836%2529%252520%25252B%252520Math.random%2528%2529.toString%252836%2529.substr%25282%2529%25253B%25250A%25250A%252520%252520%252520%252520let%252520timeout%25253B%25250A%25250A%252520%252520%252520%252520const%252520abortHandler%252520%25253D%252520%2528%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520%252520%252520clearTimeout%2528timeout%2529%25253B%25250A%252520%252520%252520%252520%252520%252520cancel%2528%252522Cancelled%252522%2529%25253B%25250A%252520%252520%252520%252520%25257D%25253B%25250A%25250A%252520%252520%252520%252520const%252520acceptHandler%252520%25253D%252520%2528id%2529%252520%25253D%25253E%252520%25257B%25250A%252520%252520%252520%252520%252520%252520if%252520%2528signal%252520instanceof%252520AbortSignal%2529%252520%25257B%25250A%252520%252520%252520%252520%252520%252520%252520%252520signal.removeEventListener%2528%252522abort%252522%25252C%252520abortHandler%25252C%252520%25257B%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520once%25253A%252520true%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25257D%2529%25253B%25250A%252520%252520%252520%252520%252520%252520%25257D%25250A%252520%252520%252520%252520%252520%252520accept%2528id%2529%25253B%25250A%252520%252520%252520%252520%25257D%25253B%25250A%25250A%252520%252520%252520%252520timeout%252520%25253D%252520setTimeout%2528acceptHandler%25252C%252520delay%25252C%252520id%2529%25253B%25250A%25250A%252520%252520%252520%252520if%252520%2528signal%252520instanceof%252520AbortSignal%2529%252520%25257B%25250A%252520%252520%252520%252520%252520%252520signal.addEventListener%2528%252522abort%252522%25252C%252520abortHandler%25252C%252520%25257B%25250A%252520%252520%252520%252520%252520%252520%252520%252520once%25253A%252520true%25250A%252520%252520%252520%252520%252520%252520%25257D%2529%25253B%25250A%252520%252520%252520%252520%25257D%25250A%252520%252520%25257D%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Dconst%25252520randomId%25252520%2525253D%25252520%252528signal%25252520%2525253D%25252520null%2525252C%25252520delay%25252520%2525253D%252525203000%252529%25252520%2525253D%2525253E%2525250A%25252520%25252520new%25252520Promise%252528%252528accept%2525252C%25252520cancel%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520const%25252520id%25252520%2525253D%25252520Date.now%252528%252529.toString%25252836%252529%25252520%2525252B%25252520Math.random%252528%252529.toString%25252836%252529.substr%2525282%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520let%25252520timeout%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520const%25252520abortHandler%25252520%2525253D%25252520%252528%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520clearTimeout%252528timeout%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520cancel%252528%25252522Cancelled%25252522%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520const%25252520acceptHandler%25252520%2525253D%25252520%252528id%252529%25252520%2525253D%2525253E%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520if%25252520%252528signal%25252520instanceof%25252520AbortSignal%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520signal.removeEventListener%252528%25252522abort%25252522%2525252C%25252520abortHandler%2525252C%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520once%2525253A%25252520true%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520accept%252528id%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520timeout%25252520%2525253D%25252520setTimeout%252528acceptHandler%2525252C%25252520delay%2525252C%25252520id%252529%2525253B%2525250A%2525250A%25252520%25252520%25252520%25252520if%25252520%252528signal%25252520instanceof%25252520AbortSignal%252529%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520signal.addEventListener%252528%25252522abort%25252522%2525252C%25252520abortHandler%2525252C%25252520%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520once%2525253A%25252520true%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525250A%25252520%25252520%2525257D%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5adf5f29a5ba6354a48b38ac156da4bb/href">https://medium.com/media/5adf5f29a5ba6354a48b38ac156da4bb/href</a></iframe><blockquote>By placing an event listener on the controller signal, if available, we can cancel a promise, by calling the controller abort method.</blockquote><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb10654485df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Hidden Attribute with React]]></title>
            <link>https://medium.com/evolve-technology/hide-that-da6264a7e1f?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/da6264a7e1f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-suspense]]></category>
            <category><![CDATA[hidden]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 12:01:39 GMT</pubDate>
            <atom:updated>2019-07-16T06:19:06.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time a React component mounts, updates or is unmounted, React executes two phases:</p><ul><li>A render phase</li><li>A commit phase</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cPZQuuy2-UK917bV" /><figcaption>Photo by <a href="https://unsplash.com/@medbadrc?utm_source=medium&amp;utm_medium=referral">Med Badr Chemmaoui</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is a cause-effect relation between these two. The render phase is a pure, side-effect free phase, in which React collects updates, or attempts to set state on components.</p><blockquote>In the future you’ll be able to bail on render phases.</blockquote><p>The commit phase is responsible for running side-effects, and committing changes to the DOM. After React commits to the DOM, the <a href="https://developers.google.com/web/fundamentals/performance/rendering/">Browser’s job</a> is to apply CSS styles, layout calculations, paint pixels and compose your elements into layers.</p><p>That’s a lot of work!</p><p>Luckily, there is a DOM attribute called hidden, which you can use to get React to commit changes to the DOM, while also telling the browser not to run its own work, just yet.</p><p>It is equivalent to display: none, in fact, setting a display property on hidden elements overrides the attribute!</p><p>You may think that visibility:none should work the same way, but this is a CSS property, which means the browser it’s actually execute its work chain.</p><h3>A demonstration</h3><p>Even though <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden">MDN</a> recommends not to use hidden to hide panels, it is a great way to show how to take advantage of this attribute.</p><p>In this <a href="https://hidden-attribute.surge.sh/">demo</a>, there are three tabs:</p><ul><li>The Landing tab, simply displays a message.</li><li>The Bitcoin tab, loads data from <a href="https://www.coindesk.com/api">CoinDesk</a> and shows it in a <a href="https://formidable.com/open-source/victory/docs">Victory Chart</a>.</li><li>The Pokémon tab, loads Pokémon from <a href="https://pokeapi.co/">PokeApi</a> and shows their sprites.</li></ul><blockquote><a href="https://github.com/icyJoseph/hidden-attribute">Show me the code</a></blockquote><p>Each tab is a separate JavaScript bundle to React&#39;s lazy. Since the Bitcoin tab uses <a href="https://formidable.com/open-source/victory/docs/">Victory Charts</a>, the bundle is heavy and will most likely load last. The demo uses <a href="https://parceljs.org/">Parcel</a> to bundle the whole application with zero configuration. The screenshots below are taken under Fast 3G and 6x slowdown on CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwSQTxn8yBa43eYabyjkHQ.png" /><figcaption>Suspense Landing mounts.</figcaption></figure><p>After each bundle is loaded, it is parsed, then the actual component is mounted and its own life cycles methods are executed. On mount, the Landing tab does nothing special, however, in the Pokemon tab, fire type Pokémon are queried, and in the Bitcoin tab a request for the BTC/SEK rates during the last month is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tO-FX3U9c1FJv0287gBOFA.png" /><figcaption>The Bitcoin tab takes a lot of time to parse after its lazily loaded.</figcaption></figure><p>All of this is done before the user has switched tabs. Under normal network and CPU conditions, it all happens as they read the Landing tab message.</p><p>In the Pokémon tab, elements with an even index order load their Pokémon sprite as CSS background-image, while the ones with an odd index load the sprite as an img HTML element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DU9NxL9bL_BeUkLSctMjYg.png" /><figcaption>On the left the actual Landing mounts. To the right the actual Pokémon component also mounts.</figcaption></figure><p>To see that the Browser is not actually spending resources in rendering hidden elements. You can observe that React commits its work to the DOM, because sprites for Pokémon with odd indexes are fetched, since these are specified in the src attribute for the img element.</p><blockquote>Notice that the Bitcoin data is also fetched.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sjs9Q5gGq58Rbtft8daQg.png" /><figcaption>On the left, Bitcoin tab mounts. To the right Pokémon tab updates and begins to fetch even indexed images.</figcaption></figure><p>In contrast, sprites for Pokémon with even indexes are not fetched, because these are used as a CSS background-image property and the hidden attribute tells the browser to not run it, just yet.</p><p>As soon as you switch to the Pokémon tab, the even indexed images are fetched. If you are in the <a href="https://hidden-attribute.surge.sh/">demo</a> page, open the network tab in your Browser’s developer tools to see it yourself.</p><p>What if you switch tabs quickly? You’ll either see the fallback, or simply see the rendered component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBFh94MfFBTXO86-mxMmFw.png" /><figcaption>All of the network traffic for the demo app. First serve our entry point, then lazy components, finally fetch Pokémon sprites and bitcoin rates data.</figcaption></figure><h3>Details of Implementation</h3><p>In the <a href="https://hidden-attribute.surge.sh/">demo</a>, the main App component looks like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28255%252C255%252C255%252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520App%28%29%252520%25257B%25250A%252520%252520return%252520%28%25250A%252520%252520%252520%252520%25253CTabs%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CTab%252520label%25253D%25257B%25253CLandingLabel%252520%25252F%25253E%25257D%252520title%25253D%252522Landing%252522%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CSuspenseLanding%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%25253C%25252FTab%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CTab%252520label%25253D%25257B%25253CBitCoinLabel%252520%25252F%25253E%25257D%252520title%25253D%252522Bitcoin%252522%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CSuspenseBitcoin%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%25253C%25252FTab%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CTab%252520label%25253D%25257B%25253CPokemonLabel%252520%25252F%25253E%25257D%252520title%25253D%252522Pokemon%252522%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253CSuspensePokemon%252520%25252F%25253E%25250A%252520%252520%252520%252520%252520%252520%25253C%25252FTab%25253E%25250A%252520%252520%252520%252520%25253C%25252FTabs%25253E%25250A%252520%252520%29%25253B%25250A%25257D&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28255%25252C255%25252C255%25252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520App%28%29%25252520%2525257B%2525250A%25252520%25252520return%25252520%28%2525250A%25252520%25252520%25252520%25252520%2525253CTabs%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CTab%25252520label%2525253D%2525257B%2525253CLandingLabel%25252520%2525252F%2525253E%2525257D%25252520title%2525253D%25252522Landing%25252522%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CSuspenseLanding%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252FTab%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CTab%25252520label%2525253D%2525257B%2525253CBitCoinLabel%25252520%2525252F%2525253E%2525257D%25252520title%2525253D%25252522Bitcoin%25252522%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CSuspenseBitcoin%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252FTab%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CTab%25252520label%2525253D%2525257B%2525253CPokemonLabel%25252520%2525252F%2525253E%2525257D%25252520title%2525253D%25252522Pokemon%25252522%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253CSuspensePokemon%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252FTab%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252FTabs%2525253E%2525250A%25252520%25252520%29%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=now" width="1024" height="473" frameborder="0" scrolling="no"><a href="https://medium.com/media/38640805b91c5700b7a21fa224a7b931/href">https://medium.com/media/38640805b91c5700b7a21fa224a7b931/href</a></iframe><p>It loads the Tabs component with three Tab children, the label prop on each will be used to generate the control button that activates the Tab.</p><blockquote>There is an advantage to passing a React component as label prop. Read more about it <a href="https://kentcdodds.com/blog/optimize-react-re-renders/">here</a>.</blockquote><p>Each Tab itself has children, which are Suspense React components. In case you have not used lazy and Suspense before, these are defined like so:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28255%252C255%252C255%252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dconst%252520LazyLanding%252520%25253D%252520React.lazy%28%28%29%252520%25253D%25253E%252520import%28%252522.%25252Fcontainers%25252FLanding%252522%29%29%25253B%25250A%25250Afunction%252520SuspenseLanding%28%25257B%252520...props%252520%25257D%29%252520%25257B%25250A%252520%252520return%252520%28%25250A%252520%252520%252520%252520%25253CReact.Suspense%252520fallback%25253D%25257B%25253Cdiv%25253ELoading...%25253C%25252Fdiv%25253E%25257D%25253E%25250A%252520%252520%252520%252520%252520%252520%25253CLazyLanding%252520%25257B...props%25257D%252520%25252F%25253E%25250A%252520%252520%252520%252520%25253C%25252FReact.Suspense%25253E%25250A%252520%252520%29%25253B%25250A%25257D&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28255%25252C255%25252C255%25252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dconst%25252520LazyLanding%25252520%2525253D%25252520React.lazy%28%28%29%25252520%2525253D%2525253E%25252520import%28%25252522.%2525252Fcontainers%2525252FLanding%25252522%29%29%2525253B%2525250A%2525250Afunction%25252520SuspenseLanding%28%2525257B%25252520...props%25252520%2525257D%29%25252520%2525257B%2525250A%25252520%25252520return%25252520%28%2525250A%25252520%25252520%25252520%25252520%2525253CReact.Suspense%25252520fallback%2525253D%2525257B%2525253Cdiv%2525253ELoading...%2525253C%2525252Fdiv%2525253E%2525257D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253CLazyLanding%25252520%2525257B...props%2525257D%25252520%2525252F%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252FReact.Suspense%2525253E%2525250A%25252520%25252520%29%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=now" width="1024" height="473" frameborder="0" scrolling="no"><a href="https://medium.com/media/eba3f762c370e41fe9b2c3276ef786a4/href">https://medium.com/media/eba3f762c370e41fe9b2c3276ef786a4/href</a></iframe><p>Now the implementation of the Tabs component. It controls which Tab children is shown, and it also generates the controls to switch between tabs.</p><p>To generate the controls the <a href="https://reactjs.org/docs/react-api.html">React Top Level API</a> is quite convenient. For instance, <a href="https://reactjs.org/docs/react-api.html">React.Children.map</a> allows us to pass children as first argument, and a function to map over each child, as second argument.</p><p>The mapping function creates a button HTML element that when clicked sets the child as current tab. The button also shows the label prop passed to Tab.</p><p>It is not absolutely necessary, but these controls are memo’d with empty dependencies, since they do not change when the current tab selection changes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28255%252C255%252C255%252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520Tabs%28%25257B%252520children%252520%25257D%29%252520%25257B%25250A%252520%252520const%252520%25255Bcurrent%25252C%252520setCurrent%25255D%252520%25253D%252520React.useState%280%29%25253B%25250A%25250A%252520%252520const%252520controls%252520%25253D%252520React.useMemo%28%25250A%252520%252520%252520%252520%28%29%252520%25253D%25253E%25250A%252520%252520%252520%252520%252520%252520React.Children.map%28children%25252C%252520%28%25257B%252520props%25253A%252520%25257B%252520label%252520%25257D%252520%25257D%25252C%252520index%29%252520%25253D%25253E%252520%28%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253Cbutton%252520key%25253D%25257Bindex%25257D%252520onClick%25253D%25257B%28%29%252520%25253D%25253E%252520setCurrent%28index%29%25257D%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%25257Blabel%25257D%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253C%25252Fbutton%25253E%25250A%252520%252520%252520%252520%252520%252520%29%29%25252C%25250A%252520%252520%252520%252520%25255B%25255D%25250A%252520%252520%29%25253B%25250A%25250A%252520%252520return%252520%28%25250A%252520%252520%252520%252520%25253C%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cdiv%25253E%25257Bcontrols%25257D%25253C%25252Fdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%25257BReact.Children.toArray%28children%29.map%28%28child%25252C%252520index%29%252520%25253D%25253E%252520%28%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253Cdiv%252520key%25253D%25257Bindex%25257D%252520hidden%25253D%25257Bindex%252520%21%25253D%25253D%252520current%25257D%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%25257Bchild%25257D%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253C%25252Fdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%29%29%25257D%25250A%252520%252520%252520%252520%25253C%25252F%25253E%25250A%252520%252520%29%25253B%25250A%25257D&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28255%25252C255%25252C255%25252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520Tabs%28%2525257B%25252520children%25252520%2525257D%29%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525255Bcurrent%2525252C%25252520setCurrent%2525255D%25252520%2525253D%25252520React.useState%280%29%2525253B%2525250A%2525250A%25252520%25252520const%25252520controls%25252520%2525253D%25252520React.useMemo%28%2525250A%25252520%25252520%25252520%25252520%28%29%25252520%2525253D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520React.Children.map%28children%2525252C%25252520%28%2525257B%25252520props%2525253A%25252520%2525257B%25252520label%25252520%2525257D%25252520%2525257D%2525252C%25252520index%29%25252520%2525253D%2525253E%25252520%28%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cbutton%25252520key%2525253D%2525257Bindex%2525257D%25252520onClick%2525253D%2525257B%28%29%25252520%2525253D%2525253E%25252520setCurrent%28index%29%2525257D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257Blabel%2525257D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252Fbutton%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%29%29%2525252C%2525250A%25252520%25252520%25252520%25252520%2525255B%2525255D%2525250A%25252520%25252520%29%2525253B%2525250A%2525250A%25252520%25252520return%25252520%28%2525250A%25252520%25252520%25252520%25252520%2525253C%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525257Bcontrols%2525257D%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257BReact.Children.toArray%28children%29.map%28%28child%2525252C%25252520index%29%25252520%2525253D%2525253E%25252520%28%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cdiv%25252520key%2525253D%2525257Bindex%2525257D%25252520hidden%2525253D%2525257Bindex%25252520%21%2525253D%2525253D%25252520current%2525257D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257Bchild%2525257D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%29%29%2525257D%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252F%2525253E%2525250A%25252520%25252520%29%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=now" width="1024" height="473" frameborder="0" scrolling="no"><a href="https://medium.com/media/8348c550819959088b9f4a4353a57e53/href">https://medium.com/media/8348c550819959088b9f4a4353a57e53/href</a></iframe><p>Another <a href="https://reactjs.org/docs/react-api.html">React top level API</a> is <a href="https://reactjs.org/docs/react-api.html">React.Children.toArray</a>, which returns children as an array. In this case, to generate the Tabs content, map over the array, wrapping all children with a div HTML element, where the hidden attribute equals the strict inequality result of index and current.</p><p>It is generally a bad practice to use the index as key for React elements, but for this demonstration it is good enough. Good practice would be to use a unique id prop, or the title prop, if it could be guaranteed to be unique.</p><p>The Tab component simply renders the title prop and its children.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28255%252C255%252C255%252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520Tab%28%25257B%252520title%25252C%252520children%252520%25257D%29%252520%25257B%25250A%252520%252520return%252520%28%25250A%252520%252520%252520%252520%25253C%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Ch3%25253E%25257Btitle%25257D%25253C%25252Fh3%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cdiv%25253E%25257Bchildren%25257D%25253C%25252Fdiv%25253E%25250A%252520%252520%252520%252520%25253C%25252F%25253E%25250A%252520%252520%29%25253B%25250A%25257D&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28255%25252C255%25252C255%25252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520Tab%28%2525257B%25252520title%2525252C%25252520children%25252520%2525257D%29%25252520%2525257B%2525250A%25252520%25252520return%25252520%28%2525250A%25252520%25252520%25252520%25252520%2525253C%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Ch3%2525253E%2525257Btitle%2525257D%2525253C%2525252Fh3%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525257Bchildren%2525257D%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252F%2525253E%2525250A%25252520%25252520%29%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=now" width="1024" height="473" frameborder="0" scrolling="no"><a href="https://medium.com/media/607b2bd3cb0629cef2d80b3a561616a3/href">https://medium.com/media/607b2bd3cb0629cef2d80b3a561616a3/href</a></iframe><p>Rendering the children, begins the suspenseful loading of each tab. When these resolve, React renders and commits each to the DOM. However, only the current selection is displayed, the rest are hidden.</p><h3>Counter Approach</h3><p>Another approach is to hide each tab with a Boolean flag:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%28255%252C255%252C255%252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520Tabs%28%25257B%252520children%252520%25257D%29%252520%25257B%25250A%252520%252520const%252520%25255Bcurrent%25252C%252520setCurrent%25255D%252520%25253D%252520React.useState%280%29%25253B%25250A%25250A%252520%252520const%252520controls%252520%25253D%252520React.useMemo%28%25250A%252520%252520%252520%252520%28%29%252520%25253D%25253E%25250A%252520%252520%252520%252520%252520%252520React.Children.map%28children%25252C%252520%28%25257B%252520props%25253A%252520%25257B%252520label%252520%25257D%252520%25257D%25252C%252520index%29%252520%25253D%25253E%252520%28%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253Cbutton%252520key%25253D%25257Bindex%25257D%252520onClick%25253D%25257B%28%29%252520%25253D%25253E%252520setCurrent%28index%29%25257D%25253E%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%25257Blabel%25257D%25250A%252520%252520%252520%252520%252520%252520%252520%252520%25253C%25252Fbutton%25253E%25250A%252520%252520%252520%252520%252520%252520%29%29%25252C%25250A%252520%252520%252520%252520%25255B%25255D%25250A%252520%252520%29%25253B%25250A%25250A%252520%252520return%252520%28%25250A%252520%252520%252520%252520%25253C%25253E%25250A%252520%252520%252520%252520%252520%252520%25253Cdiv%25253E%25257Bcontrols%25257D%25253C%25252Fdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%25257BReact.Children.toArray%28children%29.map%28%25250A%252520%252520%252520%252520%252520%252520%252520%252520%28child%25252C%252520index%29%252520%25253D%25253E%252520index%252520%25253D%25253D%25253D%252520current%252520%252526%252526%252520%25253Cdiv%252520key%25253D%25257Bindex%25257D%25253E%25257Bchild%25257D%25253C%25252Fdiv%25253E%25250A%252520%252520%252520%252520%252520%252520%29%25257D%25250A%252520%252520%252520%252520%25253C%25252F%25253E%25250A%252520%252520%29%25253B%25250A%25257D&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%28255%25252C255%25252C255%25252C1%29%26t%3Dseti%26wt%3Dnone%26l%3Djsx%26ds%3Dtrue%26dsyoff%3D11px%26dsblur%3D8px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D18px%26ph%3D20px%26ln%3Dfalse%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520Tabs%28%2525257B%25252520children%25252520%2525257D%29%25252520%2525257B%2525250A%25252520%25252520const%25252520%2525255Bcurrent%2525252C%25252520setCurrent%2525255D%25252520%2525253D%25252520React.useState%280%29%2525253B%2525250A%2525250A%25252520%25252520const%25252520controls%25252520%2525253D%25252520React.useMemo%28%2525250A%25252520%25252520%25252520%25252520%28%29%25252520%2525253D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520React.Children.map%28children%2525252C%25252520%28%2525257B%25252520props%2525253A%25252520%2525257B%25252520label%25252520%2525257D%25252520%2525257D%2525252C%25252520index%29%25252520%2525253D%2525253E%25252520%28%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cbutton%25252520key%2525253D%2525257Bindex%2525257D%25252520onClick%2525253D%2525257B%28%29%25252520%2525253D%2525253E%25252520setCurrent%28index%29%2525257D%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525257Blabel%2525257D%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%2525253C%2525252Fbutton%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%29%29%2525252C%2525250A%25252520%25252520%25252520%25252520%2525255B%2525255D%2525250A%25252520%25252520%29%2525253B%2525250A%2525250A%25252520%25252520return%25252520%28%2525250A%25252520%25252520%25252520%25252520%2525253C%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525253Cdiv%2525253E%2525257Bcontrols%2525257D%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257BReact.Children.toArray%28children%29.map%28%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%28child%2525252C%25252520index%29%25252520%2525253D%2525253E%25252520index%25252520%2525253D%2525253D%2525253D%25252520current%25252520%25252526%25252526%25252520%2525253Cdiv%25252520key%2525253D%2525257Bindex%2525257D%2525253E%2525257Bchild%2525257D%2525253C%2525252Fdiv%2525253E%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%29%2525257D%2525250A%25252520%25252520%25252520%25252520%2525253C%2525252F%2525253E%2525250A%25252520%25252520%29%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=now" width="1024" height="473" frameborder="0" scrolling="no"><a href="https://medium.com/media/96d70008962573ac1a1175cf57b904b5/href">https://medium.com/media/96d70008962573ac1a1175cf57b904b5/href</a></iframe><p>Unfortunately, this actually prevents the tabs from being loaded, rendered and committed to the DOM.</p><p>With this implementation, switching tabs triggers the fallback on Suspense, and makes users wait until the lazy loading resolves, it then renders and commits to the DOM.</p><p>After that, mount life cycle is executed and data is fetched. Finally, when the network requests resolve, the component is updated, triggering render and commit once again.</p><p>Moving away from a tab, will cause the component to be unmounted. If you navigate back, it will need to be mounted, and updated once again. Caching the network response might be helpful here.</p><p>To get around these issues, one could pass the hidden flag to the component and return null while it is hidden. This would allow life cycles to occur, but it requires coupling the tab management with your component’s logic.</p><p>In summary, the hidden HTML attribute helps you to:</p><ul><li>Create a better user experience.</li><li>Reduce the amount of API calls executed.</li><li>Abstract away tab management logic.</li><li>Commit work to the Browser, but save resources if its not relevant yet.</li></ul><p>The code for this demo lives in this <a href="https://github.com/icyJoseph/hidden-attribute">repository</a>.</p><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da6264a7e1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/evolve-technology/hide-that-da6264a7e1f">Using the Hidden Attribute with React</a> was originally published in <a href="https://medium.com/evolve-technology">Evolve Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useMemo — useCallback]]></title>
            <link>https://medium.com/@icjoseph/usememo-usecallback-7d164b9485f1?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d164b9485f1</guid>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Thu, 02 May 2019 16:06:07 GMT</pubDate>
            <atom:updated>2019-06-14T09:47:06.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to useMemo — useCallback</h3><p>There are two hooks which can help you stop unnecessary rendering of React Components. These are useMemo and useCallback.</p><p>In this post we understand what do they really do for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VYvlyEgPj4GtIdHP" /><figcaption>Photo by <a href="https://unsplash.com/@wimvanteinde?utm_source=medium&amp;utm_medium=referral">Wim van &#39;t Einde</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>useMemo</h3><p>Returns a value.</p><p>This hook is all about optimizing each run inside a component. This is not a cache. React will clear it whenever it thinks is necessary, and calculate the value again. Hence, it should be a pure function, which depends on internals of your component.</p><h3>useCallback</h3><p>Returns a function.</p><p>This hook is all about preventing new instances, as far as I understand it. This is not going to save previous calls and return from a cache.</p><p>With new instances I mean that the callback will only be a new function if its dependencies change. Otherwise it will be the same memory reference and children consuming it will not a see a new prop coming in.</p><h3>Demo Time</h3><p>It is better to see an example.</p><p><a href="https://codesandbox.io/s/github/icyJoseph/how-to-useCallback">how-to-usecallback - CodeSandbox</a></p><p>If you feel more comfortable working on your editor, here is a repository with the same code.</p><p><a href="https://github.com/icyJoseph/how-to-useCallback">icyJoseph/how-to-useCallback</a></p><p>There is three parts to this demo. App, Counter and Expensive.</p><p>The useCallback hook is used to prevent unnecessary rendering of a children component. The hook, useMemo is used to show how React help us prevent unnecessary calculations inside a component.</p><p><strong>Counter</strong></p><p>This function component simply takes a count and shows it. It also give the user two buttons to increase or decrease the count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWLnK9_EB-5SbHyQm3CkFA.png" /></figure><p>Mind that this component does not hold a count state itself!</p><p><strong>Expensive</strong></p><p>This so called Expensive component receives two props, total and totalCb. The latter is called when the user clicks the calculate total button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtBTe33m1UPKCLXlLsYYOw.png" /><figcaption>The Expensive Component!</figcaption></figure><p>Notice that we export Expensive wrapped by React.memo.</p><p><strong>App</strong></p><p>This component has a very special behavior. It increases a timer by one every 1000 ms and displays that update to the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOYr0T9yYUXEyf0_vop-rQ.png" /><figcaption>The App component managing, parent of Counter and Expensive.</figcaption></figure><p>When this update happens, Counter and Expensive render again. However, Expensive is wrapped by React.memo and furthermore, it takes props that have been through memoization. Therefore it does not perform an unnecessary render.</p><p>That&#39;s because:</p><ul><li>we call useCallback to generate totalCb.</li><li>total does not change unless the user increases it or decreases it inside Counter.</li></ul><p>You notice, there&#39;s a newInTheBeginning prop. This is pointing to a function defined for the whole module, so it is the same function every tick of the timer. It is defined at the top of the index.js file in case you can’t find it.</p><p>Unfortunately, if we remove the comment from the last two props,willBeNewEverytime and newEveryTime, then each tick, will make a new reference to these and hence trigger a render run, in spite of React.memo wrapping Expensive, and worst of all, that Expensive does not even know about them!</p><p>That&#39;s how useCallback helps us, it saves the reference to a function for further rendering operations. Since the reference is the same, children which consume it do not render again.</p><p>A new reference is made only if the dependencies to the callback change. In this case, that would be arrMemo. Which in turn, changes when count is modified.</p><p>Additionally we create a memoized value, by calling useMemo we can define a value derived from the count state, if we didn&#39;t useMemo, every tick would trigger a derivation!</p><p>At this point, Counter is also receiving new inc and dec props every time! Try to log from inside it and you’ll see how it render again every second!</p><p>Happy Hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d164b9485f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Odd JavaScript, destructured, part 2]]></title>
            <link>https://medium.com/@icjoseph/odd-javascript-destructured-part-2-8328f107ed2a?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8328f107ed2a</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Sat, 15 Sep 2018 23:37:02 GMT</pubDate>
            <atom:updated>2018-09-15T23:37:02.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuation from <a href="https://medium.com/@icjoseph/odd-javascript-destructured-part-1-ceda1a1fd4f">part 1</a>.</p><p>The next JavaScript oddity in the <a href="https://www.youtube.com/watch?reload=9&amp;v=W7_RWDAesK0">video</a> actually took me a while to nail and pushed me to review the ECMAScript specification and get clear on the concepts of <em>CanonicalNumericIndexString, exotic indexing and abstract operations.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AXQgFbV18nNfofg0" /><figcaption>Photo by <a href="https://unsplash.com/@templecerulean?utm_source=medium&amp;utm_medium=referral">Temple Cerulean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In case you haven’t seen the what the oddity is about, here it goes:</p><pre>&gt;const arr = new Int32Array(10);<br>undefined<br>&gt;arr<br>Int32Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]<br>&gt;arr[1] = 43;<br>43<br>&gt;arr<br>Int32Array [ 0, 43, 0, 0, 0, 0, 0, 0, 0, 0 ]</pre><p>So far so good, we created a Typed-Array, and assigned 43 to the index 1. Before continuing the with the oddity, let’s see what happens if we assign a value to index out of bounds, say 11.</p><pre>&gt;arr[11] = 11;<br>11<br>&gt;arr;<br>Int32Array [ 0, 43, 0, 0, 0, 0, 0, 0, 0, 0 ]</pre><p>Nothing was assigned. Unlike a regular JavaScript array, where something would have been added at that index, creating holes if needed.</p><p>So the oddity continues:</p><pre>&gt;arr[&#39;1.1&#39;] = 100;<br>100;<br>&gt;arr<br>Int32Array [ 0, 43, 0, 0, 0, 0, 0, 0, 0, 0 ]<br>&gt;arr.length<br>10</pre><p>Nothing happened, and we sort of expect that, correct? I print the length because not everybody knows that length of arrays has an oddity itself.</p><p>But it continues:</p><pre>&gt;arr[&#39;1.10&#39;] = 1000;<br>1000<br>&gt;arr<br>Int32Array [ 0, 43, 0, 0, 0, 0, 0, 0, 0, 0, &#39;1.10&#39;: 1000 ]<br>&gt;arr.length<br>10</pre><p>What?! we were able to add &#39;1.10&#39;:1000 to the Typed-Array. How in the heck?</p><p><strong>The length didn’t change.</strong></p><p>I put together this <a href="https://repl.it/@icyJoseph/ArtisticBoilingList">repl.it</a> to help you understand and play around with what just happened!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40icyJoseph%2FArtisticBoilingList%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40icyJoseph%2FArtisticBoilingList%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/853750e22ac020aaa80aa94777e1dc4e/href">https://medium.com/media/853750e22ac020aaa80aa94777e1dc4e/href</a></iframe><p>It all boils down to the concepts of <em>CanonicalNumericIndexString, exotic-indexing </em>and how they are being executed. The ECMAScript specifications talks about abstract operations, which have clear and concise logic, so one can read them like pseudo-code.</p><blockquote><a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-canonicalnumericindexstring">CanonicalNumericIndexString ( argument )</a></blockquote><blockquote>The abstract operation CanonicalNumericIndexString returns argument converted to a numeric value if it is a String representation of a Number that would be produced by ToString, or the string <strong>&quot;-0&quot;</strong>. Otherwise, it returns <strong>undefined.</strong> This abstract operation functions as follows:</blockquote><blockquote>Assert: Type(<em>argument</em>) is String.</blockquote><blockquote>If <em>argument</em> is <strong>&quot;-0&quot;</strong>, return −0.</blockquote><blockquote>Let <em>n</em> be ToNumber(<em>argument</em>).</blockquote><blockquote>If SameValue(ToString(<em>n</em>), <em>argument</em>) is <strong>false</strong>, return <strong>undefined</strong>.</blockquote><blockquote>Return <em>n</em>.</blockquote><blockquote>A <em>canonical numeric string</em> is any String value for which the CanonicalNumericIndexString abstract operation does not return <strong>undefined</strong>.</blockquote><p>Assuming ToString, ToNumber and SameValue, to be defined:</p><pre>function CanonicalNumericIndexString(argument) {<br>   const numericIndexString = ToString(ToNumber(argument))<br>   return SameValue(a, argument) ? true : undefined;<br>}</pre><p>When assigning values to array positions, the argument passes through the function above. Same for Typed-Arrays. If the function returns undefined then the string is used as is, otherwise as numeric-index.</p><pre>&gt;const barr = Array.from({length}, () =&gt; 0);<br>&gt;barr<br>[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]<br>&gt;barr[&#39;1.1&#39;] = 10;<br>10<br>&gt;barr[&#39;1.10&#39;] = 10;<br>10<br>&gt;barr<br>[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, &#39;1.1&#39;: 10, &#39;1.10&#39;: 10 ]<br>&gt;barr.length<br>10</pre><p>But in this case, ‘1.1’, does work! Well that’s because the ToNumber, ToString combo is using different implementations.</p><p><strong>By the way, notice how the length of </strong><strong>barr hasn’t changed, string-indices do not affect the length of the array!</strong></p><p>The implementation of ToNumber in Typed-Arrays, as I understand is running Number for ToNumber, while arrays, are using a ToUInt32 function. Exotic versus regular indexing.</p><p>This is why, the padding with zero at the end works, because it returns undefined from the Canonical function.</p><p>Actually, you can reach the point where Number breaks, at number 1.0000000000000001 which will return also undefined without padding it with a zero at the end, and will add the key 1.0000000000000001 to the Typed-Array.</p><p>A few more resources, about arrays using <a href="https://tc39.github.io/ecma262/#sec-array-exotic-objects">Int32</a>, and Typed-Arrays exotic indexing <a href="https://tc39.github.io/ecma262/#sec-properties-of-typedarray-instances">here</a> and <a href="https://tc39.github.io/ecma262/#sec-integer-indexed-exotic-objects-set-p-v-receiver">here</a>.</p><h3>NaN</h3><p>Onto the next oddity. The sentient value NaN, which is an error within the number set types, which means that:</p><pre>&gt;typeof NaN<br>&#39;number&#39;</pre><p>And it is also the only, non-reflexive value:</p><pre>&gt;NaN === NaN<br>false<br>&gt;NaN !== NaN<br>true</pre><p>That’s what it is, nothing much more to it. It is odd yes, but with rules anyway.</p><p>However:</p><pre>&gt;const arr = [NaN]<br>&gt;arr.includes(NaN)<br>true<br>&gt;arr.indexOf(NaN)<br>-1</pre><p>Why can we be sure that NaN is in arr, but can’t find its index?</p><blockquote><a href="https://tc39.github.io/ecma262/#sec-samevaluezero">7.2.11 SameValueZero ( x, y )</a></blockquote><blockquote>The internal comparison abstract operation SameValueZero(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:</blockquote><blockquote>If <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(x) is different from <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(y), return false.</blockquote><blockquote>If <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Type</a>(x) is Number, then</blockquote><blockquote>If x is NaN and y is NaN, return true.</blockquote><blockquote>If x is +0 and y is -0, return true.</blockquote><blockquote>If x is -0 and y is +0, return true.</blockquote><blockquote>If x is the same Number value as y, return true.</blockquote><blockquote>Return false.</blockquote><blockquote>Return <a href="https://tc39.github.io/ecma262/#sec-samevaluenonnumber">SameValueNonNumber</a>(x, y).</blockquote><p>The NaN value is not reflexive with Loose or Strict equals, but it is with Object.is and SameValueZero comparissons.</p><p>Given that the array method includes, uses SameValueZero, we find the NaN element, hence true. In contrast, indexOf uses Strict equality, which as we’ve said, is not reflective for NaN, hence false.</p><h3>Loose Equals on Arrays</h3><p>This one is easy.</p><p>Loose equals calls the toString method on the Array, which in turn calls the join method without arguments.</p><pre>&gt; const a = [0]<br>&gt; a.toString()<br>&#39;0&#39;<br>&gt; a.join();<br>&#39;0&#39;</pre><p>And that’s pretty much it.</p><p>It is loosely equal to itself, yes, &#39;0&#39; is equal to &#39;0&#39;, right?</p><p>It is loosely equal to not-itself, yes. Because !&#39;0&#39; is false (negation of a truthy value) and loose equals cast &#39;0&#39; and false to Numbers giving zero on both sides.</p><p>It is loosely equal to zero, yes. Again, &#39;0&#39; is cast, coerced, to Number zero and well, zero does equal zero.</p><p>It should be clear by now, our array a is not loosely equal to empty array, because, empty array would coerce to empty string, which is falsy, and different than &#39;0&#39; . This is also why zero is loosely equal to the empty array.</p><p>It is not transitive!</p><p>The next ones are quite easy to understand.</p><h3>Sort</h3><p>Sort takes a compare function as its argument. When undefined, it defaults to sorting strings, coercing everything to strings, which is why:</p><pre>&gt; const a = [190, 670, 3]<br>&gt; a.sort()<br>[190, 3, 670]</pre><p>In case it is not clear, the strings&#39;190&#39;, &#39;3&#39;, &#39;670&#39; were the sorting criteria.</p><p>If you want to sort by numbers, use a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">number comparing function</a>.</p><h3>Let’s be clear with our Arguments</h3><p>The array method map, iterates over the array with a function on which it applies three arguments.</p><ol><li>The current item during the map iteration.</li><li>The index of the current item in the array.</li><li>The array itself.</li></ol><p>So you can write a function:</p><pre>const awesome = (item, index, arr) =&gt; <br>          console.log(`${item} at ${index} from ${arr} is awesome`);</pre><p>And then:</p><pre>[1,2,3].map(awesome);</pre><p>Which is where the oddity comes in place. In this case, I’d say, it is plain misuse of JavaScript. From <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt">MDN</a>:</p><pre>parseInt(<em>string</em>, <em>radix</em>);</pre><p>When passed to map it can also be read as:</p><pre>[&#39;1&#39;,&#39;2&#39;,&#39;3&#39;].map((item, index, arr) =&gt; parseInt(item, index))</pre><p>For the first item it will work, because index is zero. However, for the other two it will fail returning NaN.</p><p>And we wrap up with a really interesting one!</p><h3>Functions, Arrow Functions, and NaN!?</h3><p>One of my favorite features of JavaScript is that functions are first class citizens. Which means they get to occupy the same place as a number or a string. Which could also cause them to be coerced.</p><p>Remember the Typed-Array? We could’ve added a function as key:</p><pre>&gt; const weird = new Int32Array(1)<br>undefined<br>&gt; weird<br>Int32Array [ 0 ]<br>&gt; weird[(a) =&gt; a] = 10;<br>10<br>&gt; weird<br>Int32Array [ 0, &#39;(a) =&gt; a&#39;: 10 ]</pre><p>Now that’s what I call exotic indexing.</p><p>So the oddity is that an arrow function gets coerced multiple times, and chained with strings.</p><p>Let’s see, first, the anonymous arrow functions is coerced to string:</p><pre>&gt; x=&gt;x<br>&gt; ~(x=&gt;x)<br>-1</pre><p>What happens here is that the Bit-wise NOT (~) operator, coerces the operand to a Number, but string is NaN. If you were to do Bit-wise NOT on a string representation of a number, then you could apply the -(x+1) formula.</p><pre>console.log(~&quot;a&quot;); // -1<br>console.log(Number(&quot;a&quot;)); // NaN<br>console.log(~NaN); // -1<br>console.log(~15); // -16<br>console.log(~&#39;15&#39;) // -16</pre><p>See, coercion, or casting, makes it all nice and clear.</p><p>Wait a minute, why is ~NaN returning minus one?!</p><p>Well because the Bit-wise NOT is taking the first 32 bits of a 64 bits element. We can peek into the binary structure of NaN, like so:</p><pre>const buf = new ArrayBuffer(8);<br>const view = new DataView(buf);</pre><pre>view.setFloat64(0, NaN);</pre><pre>let binStr = &quot;&quot;;</pre><pre>for (let i = 0; i &lt; 8; i++) {<br>binStr += <br>(&quot;00000000&quot; + view.getUint8(i).toString(2)).slice(-8) + &quot;&quot;;<br>}</pre><pre><em>// &gt; 01111111 11111000 00000000 00000000 00000000 00000000 00000000 00000000</em></pre><pre><em>// Taking the first 32 bits...<br>console.log(</em>0b00000000000000000000000000000000); // 0</pre><pre>console.log(~0b00000000000000000000000000000000); // -1</pre><p>All the credit for the code above to the great people in <a href="https://www.reddit.com/r/javascript/comments/7jr4pv/binary_representation_of_nan/">this Reddit thread</a>.</p><p>See, how the first 32 bis of NaN return zero? and well NOT that is -1.</p><p>So it makes sense that:</p><pre>&gt; -~(x=&gt;x)<br>1<br>&gt; (-~(x=&gt;x)-~(x=&gt;x))<br>2</pre><p>Yes,1 -(-1) does equal 2 .</p><p>Add that to itself and its 4 .</p><p>Add that to an object, which coerces to zero, still 4 .</p><p>And that to an array, which calls toString on the array, which in turn joins the elements of the array with an empty string:</p><pre>&gt;[&#39;b&#39;]+2+2<br>&#39;b22&#39;</pre><p>Or in our case, 22 .</p><pre>&gt;[]+ (-~(x=&gt;x)-~(x=&gt;x)) + (-~(x=&gt;x)-~(x=&gt;x))</pre><p>And that’s it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8328f107ed2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clicking the iOS body]]></title>
            <link>https://medium.com/@icjoseph/clicking-the-ios-body-2751c785a6bc?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2751c785a6bc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 14:34:34 GMT</pubDate>
            <atom:updated>2018-09-13T14:41:38.601Z</atom:updated>
            <content:encoded><![CDATA[<p>Did you know that iOS devices with touch screen, do not trigger body element click events?</p><p>That’s right, it is a design choice made by Apple, and while it may seem harmless it could easily lead you into trouble. See <a href="https://github.com/Semantic-Org/Semantic-UI-React/pull/1833#issuecomment-313713611">this example</a>, or <a href="https://github.com/material-components/material-components-web/issues/693#issuecomment-353452904">this one here</a>.</p><p>In this post I make a Modal, assuming that attaching a listener on the body for clicks will be enough to close the Modal. One can absolutely make a better portal that will not have this problem.</p><p>The point here is to trigger it and then solve it, without modifying the portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GLIWSuwW28q6tSnq" /><figcaption>Credit to <a href="https://unsplash.com/@paul_1865?utm_source=medium&amp;utm_medium=referral">Paul Zoetemeijer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The setup</h3><p>Let’s say you have created a portable Modal component, made in React. It is such that people consuming it:</p><ol><li>Only need to pass children components to it,</li><li>Forget about handling its internal state.</li></ol><p>It is a good idea then to attach the portal directly to the body, that way you are absolute sure it will come on top of everything, and it won’t disrupt consumers.</p><p>So maybe we write the Portal component like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfcc7a30afd7c1e0dfb193934f10c3af/href">https://medium.com/media/cfcc7a30afd7c1e0dfb193934f10c3af/href</a></iframe><p>The most important thing to recognize here is that we directly attach the portal to the body of document.</p><p>The user does not need to set up and extra div and you can be sure you are not colliding with anything they may have.</p><p>Next is our Modal Component, a container which actually uses the Portal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddbc2f145f438ada61c0c343c3d64c52/href">https://medium.com/media/ddbc2f145f438ada61c0c343c3d64c52/href</a></iframe><p>Pretty much a text book React component. On mount it attaches a click event listener to the body.</p><p>The callback on this listener will close the Modal. This is where the problem lies.</p><p>Now let’s put our user hat and use this Modal within a create-react-app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/730b36b60e6f01f813921d8f9df8d0eb/href">https://medium.com/media/730b36b60e6f01f813921d8f9df8d0eb/href</a></iframe><p>As promised, all you have to do is provide children components.</p><p>It will render trigger according to its position in your application. Sweet!</p><p>Let’s yarn start and go to our localhost:3000 , bam it works!</p><p>You can clone this <a href="https://github.com/icyJoseph/portable-modal">GitHub repository</a>, or play around with <a href="https://codesandbox.io/s/1rrn0rr577">this code sand box project</a>.</p><h3>BUT!</h3><p>If you open the project in an iPhone or iPad, the modal won’t close!</p><p>Well, as you can see there is a FixButton component which will take care of this for you. But what is it doing?</p><p>It calls the magical function bodyClickFix. If you’ve read any of the links I put at the top of this post, then you know that as long as we set the body cursor to pointer, we’ll regain the click events.</p><p>Since this will also trigger some annoying highlighting, we might as well also turn it off.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fcc508393ae5550b56ef251ff3bc12/href">https://medium.com/media/28fcc508393ae5550b56ef251ff3bc12/href</a></iframe><p>This awesome function, not only sets the necessary properties on the body style, but it also executes a callback, which will set our application state to fixed!</p><h3>Alternatives</h3><p>As I said earlier there are other ways to set up a fully functional portal.</p><ol><li>Do not attach a listener to the body. Instead, use the closing modal callback passed to the Portal. The outermost div in the portal should be call it on click events.</li></ol><p>2. Allow external control.</p><p>3. Listen to touch events.</p><p>Enjoy React!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2751c785a6bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Odd JavaScript, destructured, part 1]]></title>
            <link>https://medium.com/@icjoseph/odd-javascript-destructured-part-1-ceda1a1fd4f?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceda1a1fd4f</guid>
            <category><![CDATA[learn-javascript]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 20:18:52 GMT</pubDate>
            <atom:updated>2018-09-11T11:43:31.092Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I came across the following video. Needless to say, as a JavaScript advocate, I felt I had to understand every little quirk demonstrated.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FW7_RWDAesK0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DW7_RWDAesK0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FW7_RWDAesK0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/97b9dc78a389d37cfb3e2153805dc31c/href">https://medium.com/media/97b9dc78a389d37cfb3e2153805dc31c/href</a></iframe><p>Let’s do this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dq-z27W_VhUtyNCP" /><figcaption>“Learning together to be better developers!” by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>JavaScript can’t handle numbers?</h3><p>Right off the bat, the speaker hits us with a stone. JavaScript can’t be consistent with numbers. It can handle 10 or 15, but it can’t stay consistent when a 0 is prefixed. What is going on?</p><pre>$ node<br>&gt;10<br>10<br>&gt;15<br>15<br>&gt;015<br>13</pre><p>This one is quite simple.</p><p>In JavaScript octal number syntax uses leading zeroes, with a gotcha:</p><pre>&gt;0777 // Is taken as octal<br>481<br>&gt;0999 // Is not taken as octal<br>999</pre><p>It must be obvious by now why this happens. The digit 9, or any digit greater than or equal to 8, does not exist in the octal numeral system. So 015 is in fact, an octal representation of 13 decimal.</p><p>One must remember that strict mode and ES6, forbid this syntax, which is instead replaced by 0o.</p><p>Nothing is magically known, therefore here is my <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates">source</a>.</p><h3>JavaScript can’t handle large numbers?</h3><p>Alright, fair enough, 45 seconds into the video and the speaker has now given us a really hard one, because it is true.</p><p>Large numbers arithmetic does break down in JavaScript. However, we must be able to understand what is happening, it can’t just be that JavaScript is producing off-by-one errors.</p><p>It all boils down to powers of 2. To be exact, the 53rd power of 2.</p><pre>&gt; Math.pow(2,53)<br>9007199254740992 </pre><p>Recognize that number? A side from the speaker using <a href="https://github.com/tc39/proposal-numeric-separator">this syntax</a>, we have the same number. This is a 53 bits number, and it is the largest that JavaScript can handle while also being arithmetically accurate.</p><p>Nevertheless, JavaScript will not overflow or crash when numbers are added to this 53 bit monster. In this case, adding 1 to Math.pow(2,53) is creating a 54th bit, that is multiplying by 2 once again,which is causes problems to JavaScript. From this point forward, arithmetic behaves rather strange.</p><p>More information <a href="http://2ality.com/2012/07/large-integers.html">here</a>.</p><h3>Greater, less, than or equally illogical</h3><p>Now the speaker claims that JavaScript lacks algebraic properties.</p><p>What’s just happening here then?</p><pre>&gt; 0 &lt;= null<br>true<br>&gt; 0 &gt;= null<br>true</pre><p>Then null equals zero right? Wrong.</p><pre>&gt; 0 == null<br>false<br>&gt; 0 === null<br>false</pre><p>Even the almighty strict equality seems to fail. Here we have a typical case of, <a href="https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch4.md">You Don’t Know JS.</a></p><p>Abstract Relational Comparison, performs implicit coercion differently than Loose Equals or Strict Equals, because Abstract Relation Comparison first checks if the values are of type string, if not then it casts them to number, where null is coerced to zero.</p><p>Equality coerces null to undefined, because it does to number coercion on Strings, Boolean, and well, Numbers. To coerce null to a number in equality check, prefix + to it.</p><pre>&gt; 0 === +null<br>true</pre><p>So ≤ and ≥ coerce null to zero, because these first check type of null, since it is not a string, then null is coerced to number zero, while == and ===, do not apply to number coercion on null, casting it to undefined, which is not equal to zero.</p><h3>Objects are never the same, unless they actually are</h3><p>The next section is perhaps one of the most valuable take-away from the video.</p><p>In JavaScript, you should not expect object equality, ever. This is also true for arrays, and dates, which are object-like.</p><p>In essence, for objects-like, Strict Equals and Lose Equals check memory references. See:</p><pre>&gt; const obj = {id: 0, name: &#39;Joseph&#39;}<br>&gt; const notObj = {id:0, name: &#39;Joseph&#39;}<br>&gt; const objRef = obj;<br>&gt; obj === notObj<br>false<br>&gt; obj === objRef<br>true</pre><p>In the above snippet, obj and objRef share the same memory reference. If you change somehow objRef, then obj will also be changed.</p><pre>&gt; objRef.age = 20                               <br>20                                              <br>&gt; obj                                           <br>{ id: 0, name: &#39;Joseph&#39;, age: 20 }              </pre><p>Just think about this, to make objRef equal to obj you actually did do the assignment!</p><p>Evaluating object equality is quite a complex subject. You can take the approach of checking getOwnPropertyNames on the two objects to compare, each property, but if these are also objects, or functions, you’ll start to run into edge cases which are most likely not your main problem.</p><p>That’s it for now, in the next section we’ll explore array holes, sort default behavior, bit-wise operations and tricks to generate weird returns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceda1a1fd4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce your problems]]></title>
            <link>https://medium.com/@icjoseph/reduce-your-problems-f13a19117be0?source=rss-4e80af6abc1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f13a19117be0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Joseph Chamochumbi]]></dc:creator>
            <pubDate>Fri, 24 Aug 2018 13:03:52 GMT</pubDate>
            <atom:updated>2022-12-28T15:53:26.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Arrays in JavaScript include the method <em>reduce</em>, a powerful functional programming tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gL7M3DWiFAX3yhm4" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=medium&amp;utm_medium=referral">Adi Goldstein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Often one is introduced to the <em>reduce </em>method by calculating the sum of all elements in an array, like so:</p><pre>const sum = arr =&gt; arr.reduce((acc, val) =&gt; acc + val, 0);</pre><p>That is probably the worst way to show the power of reduce, and most people dismiss it over other jewels such as map or filter, or rather use libraries such as <a href="https://lodash.com/">lodash</a>, <a href="https://underscorejs.org/">underscore</a>, <a href="https://ramdajs.com/">ramdajs</a>, to get some utility functions, when in fact the number of things you can do with reduce is up to your own imagination!</p><p>At the bottom of this page you can find a <a href="https://repl.it/@icyJoseph/BurlyLimitedMode">repl.it</a> embed, which contains a series of utility functions built with reduce, including map, filter, get, asynchronous reduce, map, and filter.</p><p>Here is a bunch of awesome things you can do with reduce.</p><p>All of these utilities can be tested in this <a href="https://repl.it/@icyJoseph/BurlyLimitedMode">repl.it</a> and are available to copy from this <a href="https://gist.github.com/icyJoseph/5262c2e34ba8c7c64ea58037a33cbe56">gist</a> enjoy!</p><h3>Map &amp; Filter</h3><p>Create your own map and filter array methods.</p><p>These methods take in three arguments, but you can now modify that behavior, moreover, you can use them as a function, which allows to pipe or compose them.</p><pre>const map = (arr, fn) =&gt; arr.reduce(<br>             (acc, val, index) =&gt; acc.concat(fn(val, index)),<br>            []);</pre><pre>const filter = (arr, fn) =&gt; arr.reduce(<br>                  (acc, val, index) =&gt; (fn(val, index) <br>                                        ? acc.concat(val) <br>                                        : acc), <br>            []);</pre><h3>Get</h3><p>Given an object and a path, search the path in the object and return its value.</p><pre>const get = (obj, path, fail = null) =&gt; {<br>if (!obj) return fail;<br>return path.split(&#39;.&#39;).reduce((prev, key) =&gt; {<br>   const value = prev ? prev[key] : obj[key];<br>   return value !== undefined &amp;&amp; value !== null ? value : fail;<br>   }, undefined);<br>};</pre><h3>GroupBy &amp; GroupByAsArray</h3><p>You can also reduce over an object to group the elements by a common key, or even better, group the elements by a common key in an array, so you can run other array methods on the result.</p><pre>const groupBy = (arr, key) =&gt; {<br>   return arr.reduce((prev, curr) =&gt; {<br>          const currKey = curr[key];<br>          const prevKey = prev[currKey];<br>          return prevKey<br>                 ? { ...prev, [currKey]: prevKey.concat([curr]) }<br>                 : { ...prev, [currKey]: [curr] };<br>          }, {});<br>};</pre><pre>const groupByAsArray = (arr, key, payload = &#39;payload&#39;) =&gt; {<br>         return arr.reduce((prev, curr) =&gt; {<br>                    const currKey = curr[key];<br>                    const index = prev.findIndex(<br>                          element =&gt;  element[key] === currKey<br>                    );<br>                    const value = index !== -1<br>? [{ [key]: currKey, [payload]: [curr, ...prev[index][payload]] }]<br>: [{ [key]: currKey, [payload]: [curr] }];</pre><pre>return prev.slice(0, index)<br>                  .concat(value)<br>                  .concat(prev.slice(index+1))<br>        }, <br>   []);<br>};</pre><p>For example, the following object:</p><pre>const toGroup = [<br> {<br>   id: 0,<br>   color: &#39;blue&#39;,<br> },<br> {<br>   id: 1,<br>   color: &#39;blue&#39;,<br> },<br> {<br>   id: 2,<br>   color: &#39;red&#39;,<br> },<br>];</pre><p>Grouped as an array:</p><pre>[<br>  {<br>    &quot;color&quot;: &quot;red&quot;,<br>    &quot;payload&quot;: [<br>      {<br>        &quot;id&quot;: 2,<br>        &quot;color&quot;: &quot;red&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;color&quot;: &quot;blue&quot;,<br>    &quot;payload&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;color&quot;: &quot;blue&quot;<br>      },<br>      {<br>        &quot;id&quot;: 0,<br>        &quot;color&quot;: &quot;blue&quot;<br>      }<br>    ]<br>  }<br>]</pre><h3>Pipe</h3><p>Takes a group of functions and returns a function that takes arguments, applies them to the first function in the group, and passes the result to the next, finally returning the result of the last evaluation.</p><pre>const pipe = (...fns) =&gt; (...args) =&gt; <br>                   fns.reduce((prev, fn, index) =&gt;<br>                    (index === 0 ? fn(...args) : fn(prev)), args);</pre><h3>Compose</h3><p>Reverse pipe, takes functions in different order.</p><pre>const compose = (…fns) =&gt; (…args) =&gt;<br>               fns.reduceRight( (prev, fn, index) =&gt; <br>                   (index === fns.length — 1 <br>                      ? fn(…args) <br>                      : fn(prev)), args);</pre><h3>Asynchronous Reduce, Map and Filter</h3><p>Last, but not least, perhaps the most awesome functions you can create. Using async/await, though.</p><pre>async function reduce(arr, fn, start = []) {<br>   return arr.reduce(async (prev, val) =&gt; {<br>              const acc = await prev;<br>              const curr = await fn(acc, val);<br>              return curr;<br>          }, Promise.resolve(start)<br>  );<br>};</pre><pre>async function map(arr, fn) {<br>   return arr.reduce(async (prev, val, index) =&gt; {<br>              const acc = await prev;<br>              const curr = await fn(val, index);<br>              return acc.concat(curr);<br>          }, Promise.resolve([])<br>  );<br>};</pre><pre>async function filter(arr, fn) {<br>   return arr.reduce(async (prev, value, index) =&gt; {<br>              const acc = await prev;<br>              const condition = await fn(value, index);<br>              if (condition) return acc.concat(value);<br>              return acc;<br>          }, Promise.resolve([])<br>  );<br>};</pre><p>Again, all of these utilities can be tested in this <a href="https://repl.it/@icyJoseph/BurlyLimitedMode">repl.it</a> and are available to copy from this <a href="https://gist.github.com/icyJoseph/5262c2e34ba8c7c64ea58037a33cbe56">gist</a>, have fun!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Frepl.it%2F%40icyJoseph%2FBurlyLimitedMode%3Flite%3Dtrue&amp;url=https%3A%2F%2Frepl.it%2F%40icyJoseph%2FBurlyLimitedMode%3Flite%3Dtrue&amp;image=https%3A%2F%2Frepl.it%2Fpublic%2Fimages%2Freplit-logo-800x600.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=repl" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/209a099de5aef0f6e687fb9026d65c98/href">https://medium.com/media/209a099de5aef0f6e687fb9026d65c98/href</a></iframe><p>For modern Web Apps, using React for instance, it is ideal to reduce the number of external libraries you import, because in the end you want to deliver the smallest amount of bytes possible.</p><p>This sort of vanilla approach of making your own functions will surely help you to reduce the bytes sent to your users, while also allowing you to customize these functions to prevent crashing, handling that in other ways, or cutting down the time it takes to run your JavaScript code, and last but not least, reducing the number of dependencies in your project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f13a19117be0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>