<?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 Akhilesh Ojha on Medium]]></title>
        <description><![CDATA[Stories by Akhilesh Ojha on Medium]]></description>
        <link>https://medium.com/@ojha-akhil123?source=rss-d765f163de9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yn5mXTp0poUPEbTSgYDwbA.jpeg</url>
            <title>Stories by Akhilesh Ojha on Medium</title>
            <link>https://medium.com/@ojha-akhil123?source=rss-d765f163de9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:12:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ojha-akhil123/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[How To Create Your Own Debounce Function in React]]></title>
            <link>https://javascript.plainenglish.io/debounce-in-javascript-7715d4266542?source=rss-d765f163de9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7715d4266542</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Akhilesh Ojha]]></dc:creator>
            <pubDate>Sat, 05 Dec 2020 09:37:49 GMT</pubDate>
            <atom:updated>2020-12-09T08:16:46.383Z</atom:updated>
            <content:encoded><![CDATA[<h4>Debounce in JavaScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9h-wdzRAydBaNY7i" /><figcaption>Photo by <a href="https://unsplash.com/@kevinmueller?utm_source=medium&amp;utm_medium=referral">Kevin Mueller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today on 5th December 2020, JavaScript celebrates its 25th Birthday and I thought of explaining one of the most important topics a JavaScript Developer should know about, <strong>Debounce</strong> function.</p><h3>What is a Debounce function?</h3><p>The <strong>debounce</strong>() <strong>function</strong> forces a <strong>function</strong> to wait a certain amount of time before running again. The <strong>function</strong> is built to limit the number of times a <strong>function</strong> is called.</p><h4>But how can this be helpful?</h4><p>To understand this, let’s take an example of an auto-complete or type-ahead. (We will build our own auto-complete in this article).</p><p>So, suppose you have an autocomplete, now to show the dropdown options you will have to fire an API on each keystroke. So if I need to search “<em>Medium Articles</em>” in an autocomplete we will trigger around 14 API calls. Is this efficient? Not at all. But then how to solve this issue? This is when <strong>Debounce</strong> comes to the picture.</p><p>With the use of the debounce function, we only trigger an API when there is a time delay provided by a user when typing. If we give a delay of say 300ms and a user takes around the same time or more to type the next letter or word, we trigger an API.</p><p>This significantly reduces the number of API calls and makes our code more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*KIllpT5DNld8VyywjxRO0w.png" /></figure><h3>Creating our Project.</h3><p>Let us first build an auto complete project which calls API on each keystroke and then improve it using our <strong>own custom Debounce</strong> function. In the end, we will also see how to use the inbuilt <strong>Debounce </strong>function which is provided to us by <strong>lodash</strong>.</p><h3>Backend code</h3><p>For this, I have created a short backend using <strong>node</strong> which gives us words according to the query param (“search string”) provided. You can also use some free APIs for the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d7fb4263bb2be84be159744f12bd6b3/href">https://medium.com/media/0d7fb4263bb2be84be159744f12bd6b3/href</a></iframe><h3>React code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d80b8895c69221d601d542b55d617b0/href">https://medium.com/media/6d80b8895c69221d601d542b55d617b0/href</a></iframe><p>This is just a simple code where we call the API on every key stroke, onChange of our input</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWo1KfZX4AzV9qqP4rW8xg.png" /></figure><h3>Creating our own Debounce Function</h3><p>Now comes the fun part. We will first build our own debounceFunction. <br><em>One thing to keep in mind is that this function should return a function.</em> <br>Our debounceFunction will take two arguments, first the function which you need to call when there is a delay (in our example the getDropDown function) and second, the delay amount for calling that function. (delay between the two keypress events)<br>Now instead of calling getDropDown function directly, we wait for the delay time. This can be achieved by using setTimeout()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/505727e581f21ae251a0f908038cbcd4/href">https://medium.com/media/505727e581f21ae251a0f908038cbcd4/href</a></iframe><p>Now to fix the context of this and to pass on the arguments to our function of getDropDown, we should call getDropDown function with apply.</p><p>Now to stop calling our function again and again, we will have to clear the timeout. Our final debounceFunction should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa9bdc9a614007e005d1779ea65c8b1/href">https://medium.com/media/6aa9bdc9a614007e005d1779ea65c8b1/href</a></iframe><p>So now on our onInputChangeHandler we can call our debounceFunction.</p><pre>const onInputChangeHandler = (e) =&gt; {<br>    const nextValue = e.target.value<br>    setSearchString(nextValue);<br>    const debounceDropdown = debounceFunction(getDropDown , 1000);<br>    debounceDropdown();<br>}</pre><h4>But will this work now?</h4><p>The answer to this is NO. Because whenever we are calling onInputChangeHandler we are creating a fresh debounceFunction that is being invoked on every keystroke and since we are calling the fresh debounceFunction every time, we are loosing the reference to the older debounceFunction and that is why it will loose its value.</p><p>To fix this, we will need the <a href="https://reactjs.org/docs/hooks-reference.html"><strong>useCallback</strong></a> hook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef22207d4048fe74376a7bd8ffbcd7b1/href">https://medium.com/media/ef22207d4048fe74376a7bd8ffbcd7b1/href</a></iframe><p>This should solve our problem. We will now call the API once there is a delay of 1 sec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeHXmRpAz53ol5TK2V2DHQ.png" /></figure><h3>Debounce using lodash</h3><p>Now, instead of creating a debounce function from scratch using can also directly use it from the <a href="https://www.npmjs.com/package/lodash.debounce">lodash package</a></p><p>To do this first install the package using</p><pre>npm i --save lodash.debounce</pre><p>Then we will import it in our App.js</p><pre>import debounce from &#39;lodash.debounce&#39;;</pre><p>Now instead of adding our custom function in <strong>useCallback</strong> you can just use the <strong>debounce</strong> provided by <strong>lodash</strong>.</p><pre>const debounceDropDown = useCallback(debounce((nextValue) =&gt; getDropDown(nextValue), 1000), [])</pre><p>Finally our App.js should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3b2c1d7a1a002949d5919b683e7452/href">https://medium.com/media/6e3b2c1d7a1a002949d5919b683e7452/href</a></iframe><h3>Conclusion</h3><p>We have now learned what <strong>Debounce</strong> function is and how to create a custom debounce function. There is a similar concept called <strong>Throttle. </strong>I’ll try to explain what Throttle is and how to implement it in a scenario in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7715d4266542" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/debounce-in-javascript-7715d4266542">How To Create Your Own Debounce Function in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement A Linked List In JavaScript.]]></title>
            <link>https://ojha-akhil123.medium.com/how-to-implement-a-linked-list-in-javascript-28e5d9fa9cc1?source=rss-d765f163de9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28e5d9fa9cc1</guid>
            <category><![CDATA[singly-linked-list]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Akhilesh Ojha]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 06:43:46 GMT</pubDate>
            <atom:updated>2020-10-11T07:48:01.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wvrp_rOs7lcY5X1i2w7DHQ.jpeg" /></figure><p>After going through the title you might think, why are we even using JavaScript to implement a Linked List, why can’t we just use C++ or Java which support prebuilt DS functions? To be honest, you are not wrong, JavaScript does not support Object-Oriented Programming (OOP) and it does not have any built-in functions for any Data Structures (except Arrays), however with ES-2015, a new <strong>class </strong>keyword was introduced and we will be taking advantage of that. But again, is implementing Data Structures really hard &amp; is it even worth our efforts? <br>You will get an answer to this once you go through this article.</p><p>Through this article we will try to understand and implement the following:</p><ul><li>What is a Linked List?</li><li>How to implement <strong>Push and Pop </strong>functionality in a Linked List?</li><li>How to implement <strong>Shift and Unshift</strong> functionality in a Linked List?</li><li>How to <strong>Insert and Delete</strong> a node at any given position in a Linked List?</li><li>How to <strong>Reverse </strong>a Linked List?</li><li>What are the <strong>advantages </strong>of using a Linked List and where might we use it?</li></ul><h3>What is a Linked List?</h3><p>To answer that we will first see what actually do we mean by a Data Structure. <strong>Data structures</strong> are a collection of values, the relationship among them, which enables efficient access and modification to our data.</p><p><em>So Linked List is a data structure that consists of nodes, and each node has a value and pointer to another node or null. <br></em><strong><em>Head </em></strong><em>is what we refer to as the starting node of Linked List and </em><strong><em>Tail </em></strong><em>is what we call the last node.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*vTsmoqKuDEUEoQjv1GJFOQ.png" /></figure><p>As we now know that Linked List is just a collection of nodes, let’s start with creating a node class. A node class will have the property of its value and the next node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c43f0ddc5d8bfe95dee03cc37ca0a82/href">https://medium.com/media/9c43f0ddc5d8bfe95dee03cc37ca0a82/href</a></iframe><h3>LinkedList Class.</h3><p>Our Class will have three main parameters,<strong> head, tail,&amp; length</strong>. By default, the value of head &amp; tail will be null and the value of length will be 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7bbb1b6d1a082654d3cdcbd184b9989/href">https://medium.com/media/e7bbb1b6d1a082654d3cdcbd184b9989/href</a></iframe><h3>Push &amp; Pop</h3><p>Push &amp; pop is used to add or delete a node at the end of the list.</p><h4>Push:</h4><p>With Push, we add a node at the end of our list.</p><h4>Algorithm:</h4><ul><li>Check for the length, if the length is 0, then, the head &amp; the tail will point to the newly created node.</li><li>If length is greater than 0, the next property on the tail will then be assigned to the <strong>new node</strong>, and the tail will then be assigned to our newly created node.</li><li>Increment the length by 1.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82952c6825a4e8cc7e09d56f27015586/href">https://medium.com/media/82952c6825a4e8cc7e09d56f27015586/href</a></iframe><pre>let list = new SinglyLinkedList();<br>list.push(30);<br>list.push(31);<br>list.push(32);</pre><h4>POP</h4><p>With <strong>pop</strong>, we can delete the last node in the linked list.</p><h4>Algorithm:</h4><ul><li>Check for the length of the list, if the length is 0, return undefined.</li><li>Loop through the list until you reach the tail.</li><li>Set the next property of second to the last node as null.</li><li>Set the tail to be the second to the last node.</li><li>Decrement the length by 1.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/293af2f33171c88ea2c65fb53ac9bc44/href">https://medium.com/media/293af2f33171c88ea2c65fb53ac9bc44/href</a></iframe><pre>list.pop();</pre><h3>Shift &amp; Unshift</h3><p>Push &amp; Pop is used for adding and removing a node from the end of the list. Contrary to this, shift &amp; unshift is used to remove and add a node from the start of the list.</p><h4>Shift:</h4><p>With <strong>Shift</strong>, we can remove the starting node.</p><h4>Algorithm:</h4><ul><li>Check for the length of the list, if the length is 0, return undefined.</li><li>Store the current head property in a variable.</li><li>Assign the head value to the current head’s next node.</li><li>Decrement the value by one.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/756f24b1f74052ac7f2ce1c70b94772d/href">https://medium.com/media/756f24b1f74052ac7f2ce1c70b94772d/href</a></iframe><pre>list.shift();</pre><h4>Unshift:</h4><p>With unshift, we add a node at the beginning of the list.</p><h4>Algorithm:</h4><ul><li>Create a new node using the value passed to the unshift function.</li><li>If length is 0, then assign the head &amp; the tail property to the newly created node.</li><li>Else, set the newly created node’s next property to the current head.</li><li>Assign the head value to the newly created node.</li><li>Increment the length by 1.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9aa098fed4d1fe6553062091e3f3e3b/href">https://medium.com/media/f9aa098fed4d1fe6553062091e3f3e3b/href</a></iframe><pre>list.unshift(10);<br>list.unshift(20);</pre><h3>Insert a node at a given position in a linked list.</h3><p>Here is when the Linked list becomes a bit difficult. With insertion, we will pass two values, the position/index where we want to add a node &amp; the value of the particular node.</p><p><strong><em>A side note: </em></strong><em>A linked list with only one element will have a length of 1 &amp; index/position of 0.</em></p><h4>Algorithm:</h4><ul><li>If the index is less than 0 or greater than the length, return undefined.</li><li>If the index is equal to the length, <strong>PUSH </strong>the new node.</li><li>If the index is equal to 0, <strong>UNSHIFT </strong>the new node.</li><li>Else, Loop through the list until you reach the <strong>index -1</strong> Node.</li><li>Set the next property on that node to our newly created node.</li><li>Set the next property of the new node to be the previous node’s (index -1 ) next.</li><li>Increment the length by 1.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6faae997a5dc58fd3a690559e98e672b/href">https://medium.com/media/6faae997a5dc58fd3a690559e98e672b/href</a></iframe><pre>list.push(10);<br>list.push(20);<br>list.<strong>insert</strong>(1 , 15)<br><strong><em>// O/p =&gt; 10 -&gt; 15 -&gt; 20</em></strong></pre><h3>Remove a node from the given position.</h3><p>When removing a node from a given position, we need to pass an index/position value to our remove function.</p><h4>Algorithm:</h4><ul><li>If the index is less than zero or greater and equal to the length, return undefined.</li><li>If the index is equal to length-1, perform the <strong>POP </strong>operation.</li><li>If the index is equal to zero, perform <strong>SHIFT </strong>operation.</li><li>Else, Loop through the list until you reach the <strong>index -1</strong> Node.</li><li>Set the next property of that Node to be the<strong> next of the next</strong> node.</li><li>Decrement the length by 1.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36b589a1e55b5b3ea5b25c71678762ed/href">https://medium.com/media/36b589a1e55b5b3ea5b25c71678762ed/href</a></iframe><pre>list.push(20); <br>list.push(30); <br>list.push(40);<br>list.removeNode(1);</pre><pre><strong>O/P -&gt; &quot;30 removed from index 1&quot;</strong></pre><h3>Reverse a Linked List.</h3><p>Here we have to reverse a linked list in place, we can’t make a copy or a duplicate and simply return that. So we <strong>Reverse </strong>as we <strong>Traverse</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*rXzPn3hSJLdf-kqMUvjVCQ.png" /><figcaption>www.<a href="https://secureservercdn.net/160.153.138.219/b79.d22.myftpupload.com/wp-content/uploads/2015/09/reverse-of-singly-linked-list1.png">secureservercdn</a>.net</figcaption></figure><h4><strong>Algorithm:</strong></h4><ul><li>Create two variables called<strong>, previous &amp; next, </strong>and keep their values as null.</li><li>Create another variable called <strong>current </strong>and initialize it to the head property.</li><li>Now Loop through the list, loop until you have a value for current.</li><li>Now we set the <strong>next </strong>property to <strong>current&#39;s next</strong>.</li><li>The <strong>current’s next</strong> property should now point to the <strong>previous</strong>. (This is how we reverse the first element, i.e now our current’s next property will point to <strong>null</strong>)</li><li>Now assign <strong>previous to current &amp; current to next.</strong></li><li>Finally, <strong>swap the head &amp; tail</strong> value and then return the list.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5be847092eac8067182da6ee86b037d/href">https://medium.com/media/b5be847092eac8067182da6ee86b037d/href</a></iframe><p>This is one way on how we can reverse a Linked List, we can also use <strong>recursion </strong>to reverse the linked list. We are not covering the recursion part here, but do let me know if you need an article on the same &amp; I’ll be more than happy to explain it using recursion.</p><h3>Why use a Linked List?</h3><p>Linked List is a primary building block of a data structure, to implement a stack or a queue we can use a Linked List. But what other <strong>advantages</strong> does it provide?</p><ul><li><strong>Dynamic Data Structure: <br></strong>A linked list is a dynamic data structure so it can grow and shrink at runtime by allocating and deallocating memory. So there is no need to give the initial size of a linked list.</li><li><strong>Insertion and Deletion: <br></strong>Unlike in an array, we can easily Insert &amp; Delete a node in Linked List. With adding or removing an element in an array, we need to re-index all the elements present, no such operation needs to be performed when using a Linked List.</li><li><strong>No memory Wastage:<br></strong>As the size of the linked list can increase or decrease at run time so there is no memory wastage. In the case of an array, there is a lot of memory wastage, like if we declare an array of size 10 and store only 6 elements in it then space of 4 elements is wasted.</li></ul><p>With some advantages, there are some <strong>disadvantages </strong>as well, when using a linked list. Here are a few of the disadvantages.</p><ul><li><strong>Memory Usage:<br></strong>More memory is required to store elements in a linked list as compared to an array. Because in the linked list each node contains a pointer and it requires extra memory for itself.</li><li><strong>No Random Access: <br></strong>Unlike in an array, we can’t have random access in a Linked List. By random access, we mean that we can directly find out the fifth element in an array using arr[4]. To retrieve an element in a liked list, we have to traverse the entire list.</li></ul><h3>Big-O for Linked List Operations:</h3><ul><li><strong>Insertion</strong>: O(1)</li><li><strong>Removal: </strong>It depends, Best Time Complexity: O(1), else O(N)</li><li><strong>Searching: </strong>O(N)</li><li><strong>Access</strong>: O(N)</li></ul><h3><strong>Applications of linked list in the real world:</strong></h3><ol><li><strong><em>Image viewer</em></strong> — Previous and next images are linked, hence can be accessed by next and previous button.</li><li><strong><em>Previous and next page in a web browser</em></strong> — We can access the previous and next URL searched in the web browser by pressing back and next button since, they are linked as a linked list.</li></ol><h3><strong>Conclusion:</strong></h3><p>We have now learned how to implement a Linked List using JavaScript. Though these operations are not so difficult, you will still want to use programing languages that does support prebuilt DS functions. However, knowing how these operations work will give a deep insight into the Data Structures, also more importantly it will help you a lot in your interview process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e5d9fa9cc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Made Easy. Part I]]></title>
            <link>https://medium.com/swlh/docker-made-easy-part-i-ffcf03cb40eb?source=rss-d765f163de9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcf03cb40eb</guid>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Akhilesh Ojha]]></dc:creator>
            <pubDate>Sun, 04 Oct 2020 05:02:36 GMT</pubDate>
            <atom:updated>2020-10-05T10:21:14.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Made Easy. Part I.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTE9bU-9zG-uTfnl3tMzog.jpeg" /><figcaption><a href="https://hdwallpaperim.com/">https://hdwallpaperim.com/</a></figcaption></figure><p>Welcome to Part I of the Docker Series where we will learn about all the basic commands which you need to master, to then containerize your docker applications. I know learning these commands might be a bit tedious, but I have tried my best to explain everything incisively. At the end of this article, you’ll also find a cheat sheet of all the docker commands which you can refer at any point in time.</p><p>In this part of the Docker Series, we will learn the following</p><ul><li>What is Docker and why do we even use it?</li><li>What are Containers?</li><li>What are Docker Images and how to create them?</li><li>Finally, we will be creating a rudimentary NodeJS Image.</li></ul><h3>What is Docker?</h3><blockquote><a href="https://www.docker.com/"><strong>Docker </strong></a>is a set of platform as a service products that use OS-level virtualization to deliver software in packages called <strong>containers</strong>.</blockquote><h3>Why do we even need Docker?</h3><p>What is the first thing you do when you are newly appointed to an ongoing project?</p><p>Let’s see, you might have been provided with an installation setup guide for the dependencies, which you’ll need to install and configure to get all the servers up in your local. Don’t we all really hate this step?</p><p>Let me add another question. Have you ever installed all the dependencies in your first attempt?</p><p>Not sure about you, but I have failed at it every time. We get stuck with an issue, then we troubleshoot that error, we find a solution, and then re-run the installer and ta-da we now have another issue. <br>If you like troubleshooting try installing Redis in your system. <br><em>Redis is an in-memory data structure store, used as a database, cache, and message broker.<br></em><a href="https://redis.io/download">https://redis.io/download</a></p><p>Now, what if I tell you that we can bring the server up using just <strong>one command</strong>? Wouldn’t that be cool? And this is what Docker does. It helps us in bringing the server up in a fraction of seconds. <br>Just to give you a gist you can download Redis with the help of docker using just one command.</p><pre>docker run -it redis</pre><p>And yey, we have up and running instance of Redis in our system. <br>To understand Docker we first need to understand a few related terms, which are <strong>Image and Container</strong>.</p><h3>What is a Docker Image?</h3><blockquote>In Docker, everything is based on Images. An image is a combination of a file system and parameters. It is a single file with all the dependencies and configurations required to run a program.</blockquote><p>Image is also the only file that gets stored in our hard drive and at some point in time, we can use this image to create something called a <strong>container.</strong></p><h3>What is a Container?</h3><blockquote>A container is an instance of an image, which is a running program. <br>So container can also be called as a program with its own isolated set of hardware resources (a small set of memory, or space for networking &amp; own little space of hard drive space).</blockquote><p>Why not just use a Virtual Machine?:</p><ul><li><strong>OS Support:</strong> <br>Virtual machines have host OS and the guest OS inside each VM. Guest OS can be any OS, like Linux or Windows, irrespective of host OS. In contrast, Docker containers host on a single physical server with a host OS, which shares among them.</li><li><strong>Performance:<br></strong>Virtual machines are more resource-intensive than Docker containers as the virtual machines need to load the entire OS to start. The lightweight architecture of Docker containers is less resource-intensive than virtual machines.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5IAjQfbH2BWKemlVAQHYg.png" /><figcaption>Docker.com</figcaption></figure><p><em>I understand it is not easy to grasp the concept of image or container, just by going through the definition</em>. <em>Images and Containers are the absolute backbones of how docker works and we will eventually find what these really are by proceeding towards the rest of the article</em>.</p><h3>How is an Image and a Container related?</h3><p>The relationship between an Image and a Container is analogous to that of a class and an object.</p><p>When we talk about an Image, we talk about a file system. An Image will be a build-up of a <strong>file system snapshot and a startup command.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwGL7Oe9x_AG_BxyM-Pefg.png" /></figure><p>We can imagine the above screenshot as a <strong>file system</strong> of the node. Which will have a start-up command of <strong>node.exe</strong>.</p><p>When we add a Docker Image, <strong>Kernel </strong>allocates a little section of hardware for this image and copies all the file system snapshot inside it. <br>Now when we run the startup command, which is also provided by the image, we then create a new instance of an image for our container.</p><p>Now with this Image, we can create multiple instances of the container. But how do we actually do it? Let’s now begin with how we can actually create an Image and Container. Too much of theory, let the fun begin now.</p><p><em>If you want to get hands-on, I’ll recommend you install docker and run the commands to get a stronger grasp. You can download docker using this link:<br></em><a href="https://www.docker.com/get-started"><em>https://www.docker.com/get-started</em></a><em>.</em></p><h3>Let’s build our first container.</h3><p>To make our life easy, we already have almost all relevant <strong>official </strong>docker images ready to use. These official images are present in <a href="https://hub.docker.com/"><strong>Docker-hub.</strong></a></p><p>Now to make a container for these images. We just have to run a command:</p><pre>docker run &lt;image name&gt;</pre><p>Now if suppose I run :</p><pre>docker run hello-world</pre><p><em>(“Hello-world” is an official image that we can use from the docker hub which just returns &quot;Hello from Docker” as an output.)</em></p><ul><li>The <strong>docker</strong> command is specific and tells the Docker program on the Operating System that something needs to be done.</li><li>The <strong>run</strong> command is used to mention that we want to create an instance of an image, which is then called a <strong>container</strong>.</li><li>Finally, “hello-world” represents the <strong>image</strong> from which the container is made</li></ul><p>With the knowledge of what a container is, I want you to imagine what steps would have happened after we run this command.</p><ul><li><strong>First</strong>: The file system snapshot of the hello-world image would have been added to our hardware.</li><li><strong>Second</strong>: Our container then runs the startup command provided by our image, prints “Hello from Docker!” &amp; then exits.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*IjoDUNPiheS_w87eBKn-ZA.png" /></figure><h3>What exactly is the “run” command?</h3><p>The run command is responsible for creating and running a container from an image. docker run = docker create + docker start.</p><p>So we can <strong>create </strong>a container of an image using : <br><em>Creating a container will just add the file snapshot inside our hard drive.</em></p><pre>docker create &lt;image name&gt;</pre><p>When we run this command, we get the <strong>id of the container as output</strong>, we can then use that container id to <strong>start </strong>the container.<br><em>Here we give our startup command to run our container.</em></p><pre>docker start &lt;container id&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*1MfBHzE8OBYaY3rAEpIjhw.png" /></figure><p><strong><em>Just a side note</em></strong><em>: We don’t need to copy the entire container id, a few starting characters will do the job.</em></p><p><strong>Why did we not see any output though? </strong>Let’s find out!</p><h3>How to show the Output of a container using “start” command?</h3><p><em>By default, the </em><strong><em>docker runs</em></strong><em> show us all the output of the container, but the </em><strong><em>docker start</em></strong><em> is the opposite.</em></p><p>To watch the output from the container and print it to our terminal we will have to use the below command.<br>“<strong>-a</strong>” simply means to attach the terminal.</p><pre>docker start <strong>-a</strong> &lt;container id&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*C0sps0GpybpSMtf9eZONwg.png" /></figure><h3><strong>Overriding a default command (starter command)</strong></h3><p>As said earlier all the images come up with a starter command, which runs when you run the image. But what if you want to run an alternate command which needs to be executed inside the container, and not the starter command? <br>Here’s how we do it:</p><pre>docker run &lt;image name&gt; <strong>command</strong></pre><p>Now suppose we need to override the starter command of the <strong>busybox </strong>(an official docker image) image by adding any other command.<br>docker run busybox echo Hi<br>This will simply override the starting command of <strong>busybox </strong>to echo command, which will then display the output as “Hi”<br><strong><em>“ls”</em></strong><em> command list all the code inside your directory. So we can override the starter command with the </em><strong><em>ls </em></strong><em>command to see the file inside our image (You guessed it, this will be </em><strong><em>our file snapshot</em></strong><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*Hlg_4kjYvSiK6hYukYwWcg.png" /></figure><h3><strong>Listing all the containers</strong></h3><p>When we run multiple images we create containers for each image. So, to list out all the <strong>running containers</strong> we can use the below command:</p><pre>docker ps</pre><p>In this project, we have made containers using two images: <strong>hello-world &amp; busybox.<br></strong>Let’s see what our docker ps command shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQ3mu7N0ar30dwlH12gCQw.png" /></figure><p>Why are we not seeing any containers here? <br><strong>One thing which we have to always keep in mind is that the purpose of a container is to only run the starter command or the overridden default command. Once the container runs this command, it exits us back to our terminal. The purpose of that container is then completed.</strong></p><p>To see docker ps inaction let&#39;s add a default code that will not exit immediately. For example, <strong>sleep </strong>command. This command basically tells the container to sleep for the time duration provided and once the sleep time is completed then it will exit out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoFI-LrhTQC7tigow_YFjQ.png" /></figure><p>This is how we can see all the running containers. But now what if we need to <strong>see all the container</strong>, even those which have exited, we can then use the below command:</p><pre>docker ps --all</pre><p><em>This command shows us all the containers, the container which has only been created, the container which is running, and the container which has exited.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bqwIQgZg1CdKSdK4ym8zA.png" /></figure><h3>Restarting the exited container.</h3><p>Once a container stops, it does not mean it is dead, we can restart the container by the start command and providing the container id.</p><pre>docker start -a &lt;container id&gt;</pre><h3>How to stop a container?</h3><p>Suppose we run an image by providing a default command of sleep for a thousand seconds. Due to some reason we now want to stop this container. Do we need to wait for a thousand seconds? Obviously, No. To stop a running container we use the following command:</p><pre>docker stop &lt;container id&gt;<br>OR<br>docker kill &lt;container id&gt;</pre><p>Now, what is the difference here? With the <strong>stop </strong>command, the container takes some time to clean up and then shuts itself. <strong>Kill </strong>command on the other hand will stop the container instantaneously without any cleanup process.</p><h3>How to listen to the standard input of a container?</h3><p>By default, the docker container does not listen to the standard input. What do we mean by this? Suppose you have a very basic image which when runs, asks you for your name. When we enter our name in the console. The output gets printed as “Hello ‘YourName’ ”.</p><p><em>Let’s name this image as greet.</em></p><p>Now what do you think will happen if we run docker run greet ?<br><em>We will just see the output as “Hello”. </em><br><strong>No input prompt appears</strong>. Now to connect our container with the <strong>standard inputs</strong>. We use the “<strong>-i”</strong> flag in our run command.</p><p>We often see the “<strong>-i </strong>”flag combined with the “<strong>-t</strong>” flag. Or just “<strong>-it</strong>” flag. <br>The basic use case of using “<strong>-t</strong>” is just to give our standard input the feel which we might get in an actual terminal.</p><pre>docker run -i greet<br>OR<br>docker run -i -t greet<br>OR<br>docker run -it greet</pre><h3>How to execute a command in a running container?</h3><p>Let’s take an example of the “Redis” image. <br><em>Redis is an in-memory data structure store, used as a database, cache, and message broker.<br></em>When we execute docker run redis, we get our container to run. Now if suppose I need to connect to my <strong>redis-cli, </strong>I’ll have to write a command to get inside my running container. We can do that by using <strong>exec.</strong></p><pre>docker exec -it &lt;container id&gt; redis-cli</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpwtZ1dWlnpL3NSUgmXOFg.png" /></figure><p>We now have access to <strong>redis-cli</strong> inside our container.</p><p>So, the main use case of the <strong>exec </strong>command is to get the<strong> terminal/shell access</strong> in our running container. By doing so we have access to all our Linux commands (cd, ls, echo, etc) which will be extremely powerful for debugging.</p><p>We can achieve this by writing “<strong>sh</strong>” at the end of our exec command.</p><pre>docker exec -it &lt;container id&gt; sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORT-EhURIOyON6Eq6efHSw.png" /></figure><p><strong>Since you all have reached so far here’s a meme to keep you all going:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*gNbSPw5BfpA8SasGIE2dcg.png" /></figure><p>Who does not love Michael Scott? :P. Now guessing, you haven&#39;t started watching this episode (Season 4 — Episode 10) of Office, let’s move on!</p><h3>Enough on Containers, How to build an Image?</h3><p>Throughout this article we have learned a lot about containers, now it’s time to focus on Images. Till now we have only used Images that were pre-built by other developers. To create our own image we will need to create a <strong>Dockerfile.</strong></p><h3>What is a Dockerfile?</h3><p>Dockerfile is simply a text file written in a specific format, which basically has <strong>instructions &amp; arguments</strong> that <strong>Docker </strong>can understand.</p><p>The instructions are written on the left-hand side (in CAPS). Everything to the right-hand side is what we call an argument.</p><pre><strong>FROM </strong>node<br>Or<br><strong>RUN </strong>npm install</pre><p>Here FROM &amp; RUN are our instruction and “node” &amp; “npm install” are our arguments.</p><h3>How to write a Dockerfile?</h3><p>As mentioned earlier Dockerfile is used to build our image. One thing that we need to understand here is that:<br>“<strong><em>Every Docker Image must be based off from another Image</em></strong>”. <strong><em>It can be based either on an Operating System or an exiting Image.</em></strong></p><p>For example:</p><pre>FROM ubuntu // Based off from an OS</pre><pre>From node // Based off from an exiting image</pre><p>So our Dockerfile must start with a <strong>FROM </strong>command.</p><p><strong>What exactly does this FROM instruction do? </strong><br>Suppose we have a Node application for which we need to create an Image. Here the first thing that we have to do is get the node in our system. Installing node will give access to all the node commands which we can use in our Dockerfile (for example npm install), the same if you install Ubuntu, you will get access to all the ubuntu commands (for example apt-get update).</p><h3>The RUN command</h3><p>The RUN command instructs the docker to run a particular command on the image which we are creating. We get access to the image commands or OS commands with the help of FROM command. To now execute these commands we need the RUN command. <br><strong><em>A quick note, npm install will only work if you have a package.json file.</em></strong></p><pre>FROM ubuntu</pre><pre>RUN apt-get update<br>RUN apt-get install node<br>RUN npm install</pre><p>Here we build our Image with the help of Ubuntu OS and then with the help of <strong>apt-get</strong> command we install node, to then get access to <strong>npm i </strong>command<strong>.</strong></p><p>Another way to do this is by actually pulling in the Node Image in our Dockerfile.</p><pre>FROM node<br>RUN npm i</pre><h3>The CMD command</h3><p>The CMD command adds the starter command to our Image. So when we run our Image using docker run &lt;Image name&gt; It will tell our container to run the CMD command as a primary/starting command.</p><pre>FROM node<br>RUN npm i<br>CMD npm start</pre><p>CMD command is also sometimes written inside an array, and each element inside an array represents a specific command<br>CMD [“npm” , “start”]</p><h3>How to build your DockerImage?</h3><p><strong>FROM, RUN, and CMD</strong> are the main commands inside a Dockerfile. Now to convert this file into an image we have to run a final command in our Docker CLI.</p><p>The “<strong>.”</strong> in the build command is what we call the <a href="https://docs.docker.com/engine/reference/commandline/build/">build context</a>.</p><pre><strong>docker run build .</strong></pre><h3>Let’s now see everything in Action.</h3><p>Inside a new-folder add a Dockerfile and a package.json file. Your package.json should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5d72ac6192feb4706890315a88a9586/href">https://medium.com/media/d5d72ac6192feb4706890315a88a9586/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91788ba8671611baeb4a15bf2c776bc/href">https://medium.com/media/a91788ba8671611baeb4a15bf2c776bc/href</a></iframe><p>Now open your folder directory in a CLI and run the build command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XelQwWtDxfePiBOp9aeLAg.png" /></figure><p><em>Please ignore the warning messages for now. <br></em>The built number highlighted here is the id our newly created image.</p><p><strong>This is it, we have now learned how to create a very basic image.</strong></p><p>If, suppose you have missed your build number here, you can get the ids or all the images and their respective data using the below command:</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQI60xvkk1Kv7KoC8cbSdw.png" /></figure><p>We will learn about the <strong>tag </strong>in the later part of this Docker Series.</p><p>To delete an image please use the below command</p><pre>docker rmi &lt;Image id&gt;</pre><h3>Conclusion:</h3><p>This is it for Part I of this docker series. I completely understand that all this information is too much to take at once, but I suggest installing docker in your system and trying all the commands which we have discussed, this will help you get an insight of the docker functionality lucidly.</p><p>Here’s a cheat sheet for all the docker commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXSW5WuC6H88HIPyHoIWYQ.png" /><figcaption><a href="https://dockerlabs.collabnix.com/">https://dockerlabs.collabnix.com/</a></figcaption></figure><p>In the second part, we will discuss much more on Images on how to containerize a <strong>React Application</strong>.</p><p>If you have anything which is up in the air for you regarding the basics of Containers &amp; Images please add it in a comment and I’ll try to answer your queries. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcf03cb40eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/docker-made-easy-part-i-ffcf03cb40eb">Docker Made Easy. Part I</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Use Redux When We Have the Context API?]]></title>
            <link>https://medium.com/better-programming/why-use-redux-when-we-have-context-api-95be70581148?source=rss-d765f163de9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/95be70581148</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Akhilesh Ojha]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 06:56:02 GMT</pubDate>
            <atom:updated>2020-09-29T15:55:58.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Use Redux When We Have the Context API?</h3><h4>Which state management solution is right for your project?</h4><figure><img alt="Redux vs. Context API." src="https://cdn-images-1.medium.com/max/1024/1*ZFWe0OgadLpTNk7Hvmv6_g.png" /><figcaption>Photo by the author.</figcaption></figure><p><a href="https://redux.js.org/">Redux</a><strong> </strong>is a library that is used in almost every React application, but do we even need it? The simple answer to this question will be “Yes, as it helps our state management.” This is not wrong, but do we have an alternative?</p><p>Fortunately, we do. As a JavaScript developer, I have come to understand that we aren’t satisfied with just one thing. We need alternatives. That is why React 16.4 offered us the <a href="https://reactjs.org/docs/context.html#api">Context API</a>.</p><p>This article will help you understand and answer the most common questions about state management:</p><ul><li>Why can’t we just use props to manage state (prop chain)?</li><li>What is Redux and why do we use it?</li><li>How can we configure Redux to our application?</li><li>What are Context APIs?</li><li>How can we configure Context APIs using Hooks?</li><li>And finally, which option is better?</li></ul><p><em>Note: If you already know how Redux works and what a prop chain is, you can skip to the Context API part.</em></p><p>I’ll start with a demo app that will just display multiple users as well as their names and authentication status. For this, we will have three main components: an App component, a Users component, and a User component.</p><figure><img alt="Demo app with multiple users." src="https://cdn-images-1.medium.com/max/1024/1*vpck49nPXvFOMWgWayeJ-w.png" /></figure><h3><strong>App Component</strong></h3><p>This component (container) will have access to the state. Our state will have a couple of things: a users array and another a boolean field for authentication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f384a132c08dc9b937f30e1f3ea421e/href">https://medium.com/media/9f384a132c08dc9b937f30e1f3ea421e/href</a></iframe><p>We will have a<strong> </strong>Login Users button inside our App.js. When clicked, it will log in all the users (change their authentication status to true). We will then be passing the users and isAuthenticated flag via props to Users.js.</p><p>This is what our app component should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2021e158ce5077c87f032adbd5eae4b/href">https://medium.com/media/c2021e158ce5077c87f032adbd5eae4b/href</a></iframe><h3><strong>Users Component</strong></h3><p>This component will be a stateless component. Here, we will only map the users coming from the App.js and will pass the values as props to the User.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4103fc46780faf558ce01b6c1703724/href">https://medium.com/media/e4103fc46780faf558ce01b6c1703724/href</a></iframe><h3><strong>User Component</strong></h3><p>User.js just displays the data received as props from the Users.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2b34ab0a8124370d7a33d2da010e9db/href">https://medium.com/media/c2b34ab0a8124370d7a33d2da010e9db/href</a></iframe><p>This is a very basic application. Now when we press the Login User button, we change the authentication status of all three users to true.</p><figure><img alt="The same demo app, but with the users’ authentication status highlighted." src="https://cdn-images-1.medium.com/max/1011/1*9AhRAWch2fhT73e6pL0OBg.png" /></figure><h3>So What Is the Problem in This App?</h3><p>Well, we can improve one thing for sure. It might not be relevant in such a small application, but is immensely important when it comes to bigger applications. We can solve the prop chain issue.</p><h4>What is the prop chain problem exactly?</h4><p>In our application, we pass the isAuthenticated flag as a prop to Users.js and then again as a prop to User.js .</p><p>But do we even need the value of isAuthenticated in Users.js? The Users component only forwards the value of isAuthenticated. It does receive the value as a prop but doesn’t really care. This is not so great, as it simply leads to extra redundancy and makes our component less reusable since we’ll always have to pass the value of isAuthenticated to it wherever we might be using the Users component.</p><h4>Redux to the rescue</h4><p>As mentioned earlier, Redux is a JavaScript library for managing application state.</p><p>I’ll try to explain how Redux works, and after that, you might have an idea of how it can solve our prop chain issue.</p><p>So Redux works around the idea of having a central state called a store. To change the state, a component has to dispatch an action.<strong> </strong>The action is then passed on to the reducer, which changes the state of our application.</p><figure><img alt="Basic visual breakdown of how Redux works." src="https://cdn-images-1.medium.com/proxy/0*68aLnHHt5H4fzztc" /><figcaption>Photo from <a href="https://upload.wikimedia.org/wikipedia/commons/0/06/Ngrx-redux-pattern-diagram.png">Wikipedia</a>.</figcaption></figure><p>This is only a brief summary of how Redux works. Let’s get back to the question of how it will solve our prop chain problem. To understand this, let’s convert our project using Redux. To connect with Redux using React, we need to follow a certain approach:</p><ul><li>The first step here is to install redux and react-redux to our application.</li><li>The second step is to add our store. The store should be created right before our application starts, so index.js will be a nice place to add our store. So we will import { createStrore } from ‘redux’. This store then needs to be stored in a constant variable. Let’s name it store, where we will call the createStore function and pass on our reducer.</li><li>Since we need to pass our reducer, we will have to create a file for this reducer and import this file to our index.js. How will our reducer file look? As mentioned before, the state change can happen only through a reducer. So we will have an initial state present in our reducer.js. The reducer function has two parameters: the state and the action<strong> </strong>(which it will receive) from the dispatched action from the component.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fd9e8f1ea18fc7fab62668c34bec8b5/href">https://medium.com/media/3fd9e8f1ea18fc7fab62668c34bec8b5/href</a></iframe><ul><li>Our reducer is currently just returning the state. Now we can import this reducer to our index.js and pass on this reducer to the createStore function (const store = createStore(reducer)). We now have our store created. To connect this store to our React application, we need a special package, which we have already installed (react-redux). With this installed, we will have to import { Provider } from ‘react-redux’. This provider needs to wrap around our App component. The provider<strong> </strong>is a helper component that allows us to inject our store to our application.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8d6f133298c9b8f23ce22c5b525821e/href">https://medium.com/media/b8d6f133298c9b8f23ce22c5b525821e/href</a></iframe><ul><li>Now, how do we get the data from the store? Well, for that we need to connect App.js with the store. To do that, we use something called connect, which is provided by the react-redux package. connect<strong> </strong>is a higher-order function that we use in our App.js export. However, connect<strong> </strong>itself is a function that returns a function, which then takes the component as an input (export default connect()(App);). Now for the first function execution of connect, we can pass some configuration. More precisely, we pass two pieces of information. First, the part of the whole application state that we need in our component. Second, the actions we need to dispatch from the component. These two configurations are named (not necessarily with the same name, but it is the most common naming convention) mapStateToProps and mapDispatchToProps. Now we won’t be needing our local state that we used earlier in our App.js and we can also get rid of the loginHandler, as we will handle the login functionality in our reducer, which in turn is dispatched as an action from our App.js. The state value can be accessible inside our component now using this.props.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42a412dced2e70824e0152465a7c490/href">https://medium.com/media/b42a412dced2e70824e0152465a7c490/href</a></iframe><ul><li>Finally, our reducer will now return the updated state when we press the Login Users button.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52b83d9e923834dc31e3bf12b18ecbd0/href">https://medium.com/media/52b83d9e923834dc31e3bf12b18ecbd0/href</a></iframe><ul><li>Now that we have set up Redux in our application, one last thing to do here is passing the value of the isAuthentication flag from our central state directly to the User.js and not<strong> </strong>via Users.js. How can this be achieved? It’s simple. Since every component can now access the state directly (using connect), we can directly access the state value in our User.js. Try giving it a shot, but below is a reference if you are unable to do it:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1549bc4aa2edb22734ac486fb9175e4/href">https://medium.com/media/c1549bc4aa2edb22734ac486fb9175e4/href</a></iframe><p>In this way, Redux helps us solve the problem of the prop chain. This might not be relevant in such a small application, but it makes our work a lot easier when using Redux in bigger applications.</p><h3>Context APIs and useContext Hooks</h3><p>Finally, we have now arrived at the interesting part, the Context API.<strong> </strong>First, let’s find out what exactly it is.</p><p>Context APIs come into the picture when we need certain data from a certain state in multiple components, but we don’t want to pass data around multiple layers.</p><p>To achieve this, we will create a new file, auth-context.js. In this file, we will create a context object. Access to it will be provided by React.</p><pre>const authContext = React.createContext(); </pre><p>createContext allows us to initialize our context with default values. This createContext is a JavaScript object (technically, it can also be an array, string, number, etc.) that can be passed between different components. Here. we can pass the default value of isAuthenticated.</p><p><em>Note: We add this for a better autocompletion in our project.</em></p><pre>import React from &#39;react&#39;;</pre><pre>const authContext = React.createContext({<br>    isAuthenticated: false,<br>});</pre><pre>export default authContext;</pre><p>Now we can import this context anywhere in our application and it needs to wrap all the parts of your application that need access to it. We will have to wrap this by using the context import name and adding .Provider after that.</p><p>This is how our App.js render function should look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38700eba19f1f2e272184aa2b5485dd8/href">https://medium.com/media/38700eba19f1f2e272184aa2b5485dd8/href</a></iframe><p>Now we wrap our AuthContext inside our Users component. We then can access the value of isAuthenticated in our Users component and all of its child components (in our case, User.js).</p><p>There are three ways to achieve this.</p><h4><strong>Using Consumer</strong></h4><p>To achieve this, we can directly go to our User.js. Inside our render function, we can add AuthContext.Consumer. Don’t forget to import AuthContext to the area where we need access to the isAuthenticated flag. This is how our render function will now look. Now this AuthContext.Consumer is our JSX component. Since this is some JavaScript expression, we need to wrap it with curly braces. The only gotcha you have to keep in mind is that the Consumer takes a function as a child between the opening and closing tag, and this function will accept our context object. Finally, to get the isAuthenticated flag, we can get that via context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b4fe0497ca9c0f9f2b681494777f1d/href">https://medium.com/media/c5b4fe0497ca9c0f9f2b681494777f1d/href</a></iframe><h4><strong>Using contextType</strong></h4><p>The issue of using Consumer is that it only runs in the render function, but there is a high chance we need the state value in other parts of our component (e.g. componentDidMount()). We will not have access to our context there. <br>To overcome this problem, React 16.6 introduced us to a special static prop, contextType, which can be used in a class-based component (static contextType = AuthContext). Now, this allows React to automatically connect this component with our context behind the scenes. This gives a new property to us that we can use inside any part of our application: this.context. <br>To now get the authentication status, we just use:</p><pre>&lt;p&gt;AuthenticationStatus:this.context.isAuthenticated.toString()}&lt;/p&gt;</pre><h4><strong>Using useContext Hook</strong></h4><p>Finally, to use this in a<strong> </strong>function component, we can use the Hook provided by React, useContext.</p><pre>const authContext = useContext(AuthContext);</pre><p>Now we can use this authContext anywhere in our functional component to get access to isAuthenticated flag.</p><pre>&lt;p&gt;AuthenticationStatus: authContext.isAuthenticated.toString()}&lt;/p&gt;</pre><p>That’s it. We have now learned how to manage our state using Context APIs.</p><h3>Which Is Better?</h3><p>As we have now learned how both Redux and Context APIs work, we can compare them and understand their pros and cons.</p><ul><li>Bundle size: The one thing we have to keep in mind is that Redux is a third-package library that is not a part of React, and hence we need to install the dependencies — mainly three of them (redux, react-redux, redux-thunk). Using Redux comes at a cost. Installing these dependencies increases our final bundle size. On the contrary, Context APIs are a part of React, so our bundle size remains the same.</li><li>Boilerplate code: With Redux, we need to have an exhaustive setup, we need to build a store, and we need to dispatch actions. We then need to connect our store with our components. Sometimes, this is a pain for a developer. There is a high chance that one might get lost in the codes and just wander aimlessly with no clue on how to fix anything. Basically, you need to have a hands-on approach to work with Redux. According to me, Context APIs involve less boilerplate codes. With the introduction of React 16.6, we don’t even need the consumer. With just one line of code, you can get access to your context.</li><li>Handle async code: In Context APIs, triggering an API (async codes) is relatively straightforward to use once you get the hang of it (especially when using Hooks). You also don’t need a package like redux-thunk to handle asynchronous actions.</li></ul><h3>Conclusion</h3><p>With this article, you can now guess why Context APIs can be better than Redux. However, a newer version of Redux is expected to be launched. It will contain less boilerplate code and will be more efficient. Let’s wait to see how that works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95be70581148" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/why-use-redux-when-we-have-context-api-95be70581148">Why Use Redux When We Have the Context API?</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async JavaScript. Ten Minutes of Your Interview Covered.]]></title>
            <link>https://medium.com/swlh/async-javascript-ten-minutes-of-your-interview-covered-3c7204342b8a?source=rss-d765f163de9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c7204342b8a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[asyncjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Akhilesh Ojha]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 10:24:35 GMT</pubDate>
            <atom:updated>2020-09-21T18:03:40.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DLcXR0R7xhTeATodu43Gg.png" /></figure><p>Welcome to the blog where I answer the most asked JavaScript Interview question, after Life Cycles of course :P.</p><h3><strong>What are callbacks, promises, and async-await? Which one is better and how to implement these?</strong></h3><p><strong>*Also something extra for Angular Developers on what are Observables and how do they differ from Promise.*</strong></p><p>First thing first, JavaScript by default runs synchronously but then why do we need to run it asynchronously? For this to understand, let’s see how actually is the synchronous operation performed in JS.</p><p>Guess what will be the output for the below code block.</p><pre>console.log(&#39;a&#39;);<br>function callMe() {<br>   console.log(&#39;b&#39;);<br>}<br>callMe()<br>console.log(&#39;c&#39;);</pre><p>Easy, right? The output will be, a b c.</p><p>But how does this actually work? We need to first understand that JavaScript is a <strong>single-threaded</strong> programming language, which means it can perform only one action at a time. <br><em>So what happens behind the scene is that our first console.log(‘a’) gets added to the call-stack and then we print the output, in this case, ‘a’. So in short it executes the function present in the call-stack, logs the output, and removes this function from the stack. Then callMe function gets added to our call-stack and it returns the value of ‘b’ and gets removed and so on.</em></p><p>Now here the function callMe just adds a logger. What if there is a function that needs to run thousands of lines of code to return a value or an AJAX call which will take some time to bring back our data? Will we wait for the function to execute completely and then move ahead? <br>This will be a nightmare. JavaScript waits for NO ONE. And this is when Async JS comes to the picture.</p><p><strong>Consider another example where we run async codes.</strong></p><pre>console.log(&#39;a&#39;);<br>setTimeout(() =&gt; {<br>   console.log(&#39;b&#39;);<br>}, 1000);<br>console.log(&#39;c&#39;);<br>//setTimeout is a function provided by JS which does async operation</pre><p>Now as you might have expected the out will print ‘a’ then ‘c’ and after one second it prints ‘b’, but what if we pass 0 seconds as time in our setTimeout function?</p><pre>console.log(&#39;a&#39;);<br>setTimeout(() =&gt; {<br>   console.log(&#39;b&#39;);<br>}, 0);<br>console.log(&#39;c&#39;);</pre><p>Again, the output will be the same, but why? The reason is that any async function is not added to the call-stack, but to something called as <strong>Web Apis</strong> (provided by the browser, and we are running our JS in browser). So JS passes this setTimeout function in Web Apis, and not in call-stack. Again, as JS is single-threaded, it runs the next line of code. When all the synchronous processes are completed only then, we add the functions present in Web Apis to our call-stack and then execute these. So even if we pass 0 seconds in our setTimeout function, it doesn’t get added to our call-stack directly, but to the Web APIs.</p><p>As we now know how async operation runs behind the scene, let us talk about what issue we might face when we try to run a service call (faking it using setTimeout) synchronously. <br>Consider an example that a user logins and when it does, it should get a token.</p><pre>console.log(&#39;a&#39;);</pre><pre>function login(email, password) {<br>      setTimeout(() =&gt; {<br>          return {usertoken: &quot;randomId&quot;}<br>      },3000);<br>}</pre><pre>const token = login(&quot;abc@gmail.com&quot; , &quot;1234&quot;);</pre><pre>console.log(token);</pre><pre>console.log(&#39;c&#39;);</pre><p>Will I be getting my user token in this case? <br>The answer to this is no, when we call the login function, we don’t wait for its output, JS moves ahead and tries to log the token value, which is undefined in this case. But then question here is how do I get my token?</p><p>Moving forward we will look on three ways to achieve this and kicking on on list is:</p><h3><strong>Good old callbacks</strong></h3><p>Let us look at what the definition of callback really is:</p><p><em>A </em><strong><em>callback</em></strong><em> function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.</em></p><p>And what the heck did you just read!!!! Please don’t burst your head reading this again and again if you didn&#39;t understand what the definition actually says. Try understanding the below example and then come back and read the definition again!</p><p>Coming back to our login function again.<br>The first change we will have to do is pass another parameter in our login function, which will be our <strong>callback </strong>function.</p><pre>function login(email, password , <strong>callback</strong>)</pre><p>Now where we call the login function we have to add another parameter for that callback, which will be an anonymous function.</p><pre>const token = login(“abc@gmail.com” , “1234” , <strong>() =&gt; {}</strong>)</pre><p>Now inside the function login, instead of returning the token, we pass that value of the token in our callback function.</p><pre>function login(email, password , callback) {<br>      setTimeout(() =&gt; {<br>          <strong>callback</strong>({usertoken: &quot;randomId&quot;});<br>      },3000);<br>}</pre><p>That’s it, now the value (userToken) passed as an argument in the callback function can be received by the anonymous function, and we can access the<br>token value. <br>So our final code will look like this:</p><pre>console.log(&#39;a&#39;);<br>function login(email, password , callback) {<br>      setTimeout(() =&gt; {<br>          callback({usertoken: &quot;randomId&quot;});<br>      },3000);<br>}<br>const token = login(&quot;abc@gmail.com&quot; , &quot;1234&quot;, (userTokenFromCB) =&gt; {<br>      console.log(&quot;usertoken&quot; , userTokenFromCB.usertoken);<br>});<br>console.log(&#39;c&#39;);</pre><p>Our output here will be “a” then “c” and after three seconds we will log “randomId” which is basically our userToken.</p><p>So this is how callback helps us in solving the issue. But then why do we need another approach? What is the problem with not only using callback? Let’s find out.</p><p>Now suppose after my user is logged in, I need to pass my token to fetch the user details. How will my callback code look then?</p><pre>console.log(&quot;a&quot;);</pre><pre>function login(email ,password, callBack) {<br>    setTimeout(() =&gt; {<br>        callBack({userToken: &quot;randomId&quot;});<br>    }, 3000);<br>}</pre><pre>function getDetails(userToken , callBack) {<br>    setTimeout(() =&gt; {<br>        callBack({name: &quot;John Doe&quot;, dob: &quot;6th May 1995&quot;})<br>    }, 3000);<br>}</pre><pre>const details = login(&quot;abc@gmail.com&quot;, &quot;1234&quot;,(userTokenFromCB) =&gt; {<br>    const token = userTokenFromCB.userToken;<br>    getDetailsProfile( token ,(detailsFromCB) =&gt; {<br>        console.log(&#39;Details&#39;, detailsFromCB);<br>    });<br>});</pre><pre>console.log(&quot;b&quot;);</pre><p>Here we see that a chain of callback functions gets generated. Now if suppose we need the details of the user to fetch some other API (not applicable in our example) a huge chain of callback functions get generated and this is called <strong>callback hell.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fP1bDwR3yIa3iRGCRNphjA.jpeg" /></figure><p>Another problem that we face with callbacks is error handling, what if the API that we call somehow fails? To handle these errors we again have to use the callback function and you can guess where I am going with this. Also, the code readability is not so much clear when we use callbacks.</p><h3><strong>Promise to our rescue</strong></h3><p>With ES6 came promises. <strong>Promises </strong>are object which basically gives us a success of an async operation (resolve) or failure of an async operation (reject)</p><p>Here is how we define a promise.</p><pre>const promise = new Promise((resolve , reject) =&gt; {});</pre><p>Converting login function using Promise: <br>Here instead of passing token inside a callback function, we pass the token inside <strong>resolve</strong>,<strong> </strong>which is provided to us by Promise.</p><pre>function login(email , password) {<br>    return <strong>new Promise</strong>((resolve , reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            <strong>resolve</strong>({userToken: &quot;randomId&quot;}) <br>        }, 3000)<br>    })  <br>}</pre><p>Then to consume a promise we use <strong>.then</strong></p><pre>login(&quot;abc@gmail.com&quot; , &#39;1234&#39;)<br>.then(token =&gt; console.log(token));</pre><p>So now if we need to call a chain of APIs this is how our promise will look</p><pre>login(&quot;abc@gmail.com&quot; , &quot;1234&quot;)<br>.then(token =&gt; getUserDetails(token.userToken))<br>.then(details =&gt; getFriendList(details));<br>.then(friends =&gt; callAnotherAPI()) <br>//and so on.</pre><p>Now as we can see this becomes so much easier to read as we don’t have the daunting callbacks. Also to pass an error, instead of resolving it, we reject it and when we consume that promise we can use <strong>.catch</strong> to throw an error message.</p><p><strong><em>Just a side note</em></strong><em>: What basically the above lines of code do is, it takes three-second (because of setTimeout) to get the token, then it uses that token and takes three more seconds to get the details, and so on. This happens because my getDetails function is depended on the return value of the login function.</em></p><p><em>But what if I don’t need to wait, I mean suppose we need to call two different and </em><strong><em>independent</em></strong><em> service at the same time (the response of one is not related to the other). Then we can use something called </em><strong><em>Promise.all() </em></strong><em>and we pass both(or multiple promises) as an array.</em></p><pre>Promise.all([Promise1 , Promise2]).then(result=&gt;console.log(result))</pre><p>Promises are really great, it solves the issue of callback hell, it deals with error handling in a great way. But then why do we even need anything else to implement Async JS? <br><em>Well, people had some issues using </em><strong><em>“.then”</em></strong><em>,</em><strong><em> </em></strong><em>they thought it is still a kind of callback. <br>Now what everyone ( well not exactly everyone, people with high demands :P) wanted was to run async code but kind of written in a synchronous way. No </em><strong><em>.then, </em></strong><em>no </em><strong><em>callbacks</em></strong><em>,</em><strong><em> </em></strong><em>none of this. What do we use now?</em></p><h3><strong>Async Await to save our day</strong></h3><p>Async await is <strong>still based on promises, </strong>but it just has kind of new syntax to work with.</p><p>Wouldn’t it be nice to write our code something like this?</p><pre>const token = login(&quot;abc@gmail.com&quot; , &quot;1234&quot;);<br>const details = getDetails(token);</pre><p>How can we run this asynchronously though? Thanks to ES7 which introduced us to the most modern way of controlling async operations, Async Await.</p><p>So as mentioned before, we will have to declare our functions using Promises. Nothing gets changed there, the change is only when we consume these promises.</p><pre>function login(email , password) {<br>    return <strong>new Promise</strong>((resolve , reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            <strong>resolve</strong>({userToken: &quot;randomId&quot;}) <br>        }, 3000)<br>    })  <br>}</pre><pre>function getDetails(userToken) {<br>    return <strong>new Promise</strong>((resolve , reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            <strong>resolve</strong>({name: &quot;John Doe&quot;, dob: &quot;6th May 1995&quot;}) <br>        }, 3000)<br>    })<br>}</pre><p>Now to get the token and the details, the first thing we do is create a function and get the token and the details inside that function.</p><pre>function userDetails() {<br>    const token = login(&quot;abc@gmail.com&quot; , &quot;1234&quot;);<br>    const details = getDetails(token);<br>}</pre><pre>userDetails();</pre><p>This as said before will not work, the next thing we do to make this work is to write <strong>await </strong>before login and getDetails.</p><pre>function userDetails() {<br>    const token = <strong>await </strong>login(&quot;abc@gmail.com&quot; , &quot;1234&quot;);<br>    const details = <strong>await </strong>getDetails(token);<br>}</pre><pre>userDetails();</pre><p>It still won’t work, we need to inform JS that we need to run the function userDetails asynchronously. To that we have our final step, write <strong>async </strong>before the function userDetails()</p><pre><strong>async </strong>function userDetails() {<br>    const token = <strong>await </strong>login(&quot;abc@gmail.com&quot; , &quot;1234&quot;);<br>    const details = <strong>await </strong>getDetails(token);<br>    console.log(details);<br>}</pre><pre>userDetails();</pre><p>Now, this looks easy and clear to read. <br>But how can we do the error handling here? We don’t have access to “.catch”.</p><p><em>It’s simple, we use our normal </em><strong><em>try and catch block. </em></strong><em>JS tries to run the code inside the try block if it doesn’t work or it gets an error, it goes to the catch block.</em></p><pre>async function userDetails() {<br>    try {<br>         const token = await login(&quot;abc@gmail.com&quot; , &quot;1234&quot;);<br>         const details = await getDetails(token);<br>         console.log(details);<br>    }<br>    catch(err) {<br>         console.log(err);<br>    }<br>}<br>userDetails();</pre><h3>RxJs Observables</h3><p>RxJS Observable is not a native JS feature but is provided by a third-party library called “<strong>RxJs”.</strong></p><p><em>In an Observable patter we have an </em><strong><em>Observable </em></strong><em>and an </em><strong><em>Observer</em></strong><em>, in between, we have a stream of data or timeline and on this timeline, we can have multiple events emitted by Observables.</em><br><em>The </em><strong><em>observable </em></strong><em>give us three data which we have to look up to, </em><strong><em>“Handle Data”, “Handle Error”, and “Handle Completion”. </em></strong><em>The </em><strong><em>observer </em></strong><em>on the other hand has the task of being informed about these three data and act accordingly.<br>Observer then has some built-in methods to use, </em><strong><em>“.next”, </em></strong><em>to emit new values, </em><strong><em>“.error”</em></strong><em> to throw an error, and </em><strong><em>“.complete”</em></strong><em>, to let the observer know that we are done.</em></p><p>To create an observable we use <strong>Rx.Observable.create </strong>provided to us by RxJs.<br>“<strong>.create</strong>” takes in a function, which in turn takes <strong>observer </strong>as an argument.</p><pre>function login(email , password) {<br>    return <strong>Rx.Observable.create((observer)</strong> =&gt; {<br>        setTimeout(() =&gt; {<br>            <strong>observer.next</strong>({userToken: &quot;randomId&quot;}) <br>        }, 3000)<br>    })  <br>}</pre><pre>function getDetails(userToken) {<br>    return <strong>Rx.Observable.create((observer)</strong> =&gt; {<br>        setTimeout(() =&gt; {<br>            <strong>observer.next</strong>({name: &quot;John Doe&quot;, dob: &quot;6th May 1995&quot;}) <br>        }, 3000)<br>    })<br>}</pre><p>Unlike “<strong>.then” </strong>which use to execute a promise, we use “.<strong>subscribe</strong>” to listen to an observable</p><pre>login(&quot;abc@gmail.com&quot; , &quot;1234&quot;)<br>.<strong>subscribe</strong>(token =&gt; getUserDetails(token.userToken))<br>.<strong>subscribe</strong>(details =&gt; getFriendList(details))<br>//and so on</pre><p>The “.subscribe” taken in second parameter to handle errors</p><pre>login(&quot;abc@gmail.com&quot; , &quot;1234&quot;).<strong>subscribe</strong>(token =&gt; {<br>       console.log(token);<br>}, error =&gt; {<br>       console.log(error);<br>)</pre><p>Now the question, here again, is how are Observables different from Promises? <br><em>The core distinction between Promises and Observables is that Promises handle only one value, we send an HTTP request, we get a response, we resolve our Promise and then we are done. Observables on the other handle streams of data, we can wrap an Observable inside a click listener to listen to every new click and emit a new value on every new click, which is not possible by using Promise.</em></p><h3><em>CONCLUSION</em></h3><p>This is it. We now have learned how async JS works. Believe me, the chances of getting a question about this in an interview is immensely high. But be sure to explain everything with an example and not what the actual definition says. Hope this helps. :). All the best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c7204342b8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/async-javascript-ten-minutes-of-your-interview-covered-3c7204342b8a">Async JavaScript. Ten Minutes of Your Interview Covered.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refs and Forward Refs in React.]]></title>
            <link>https://medium.com/swlh/refs-and-forward-refs-in-react-be5bcb86fc69?source=rss-d765f163de9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5bcb86fc69</guid>
            <category><![CDATA[react-refs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akhilesh Ojha]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 12:20:36 GMT</pubDate>
            <atom:updated>2020-09-14T14:13:19.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwAivsjKxhgPxZJXKjip9g.jpeg" /></figure><p>React Refs are a useful feature that acts as a means to reference a DOM element.</p><p>But the question here is why can we not directly manipulate the DOM using normal JavaScript DOM Manipulation?</p><p>Here is an example of why normal JS DOM Manipulation won’t be as useful as Refs when it comes to using React.</p><p><em>Suppose you have a component which has multiple input element. Now, what if we want to focus on the second input element or any other input element as soon as we render the component?</em></p><p>What happens when we use normal JS DOM Manipulation?</p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>export class InputRef extends Component {</pre><pre>componentDidMount() {<br>  document.querySelector(&#39;input&#39;).focus();<br>}</pre><pre>render() {<br>  return (<br>    &lt;div&gt; <br>      &lt;input type=&quot;text&quot; /&gt;<br>      &lt;input type=&quot;text&quot; /&gt;<br>      &lt;input type=&quot;text&quot; /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>}<br>export default InputRef;</pre><p>Here we do indeed focus, but we always focus on the first input element. Simply because <em>document.querySelector</em> selects the first input element it finds in the entire DOM.<br>This is because<em> document.querySelector </em>is not something that is related to React but is a general DOM Selector.</p><p>We can anyway add an id to these inputs and focus according to id, but React offers a better alternative. <strong>The Refs</strong>.</p><p><strong>Refs in Class-Based Components. Old Approach.</strong></p><p>Here we pass a function (anonymous arrow function)in the input element which you want to focus on. The argument that we get is a reference to the element on which we place the function and we can use that reference in our function body.</p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>export class InputRef extends Component {</pre><pre>componentDidMount() {<br>  this.inputElRef.focus();<br>}</pre><pre>render() {<br>  return (<br>    &lt;div&gt; <br>      &lt;input type=&quot;text&quot; /&gt;<br>      &lt;input type=&quot;text&quot; ref={(inputElRef) =&gt; {this.inputElRef =  inputElRef}}/&gt;<br>      &lt;input type=&quot;text&quot; /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>}<br>export default InputRef;`</pre><p>Here this.inputElRef will store our reference in global property and hence we can access that reference anywhere in our component (in our case componetDidMount()).</p><p><strong>Since React-16.3 we now have another way of using Ref and that uses CreateRef.</strong></p><p>Here instead of passing a function to Ref, we can directly assign the value that we have using <strong>createRef </strong>to our input element.</p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>export class InputRef extends Component {</pre><pre>constructor(props) {<br>  super(props);<br>  this.inputElRef = React.createRef();<br>}</pre><pre>componentDidMount() {<br>  this.inputElRef.current.focus();<br>}</pre><pre>render() {<br>  return (<br>    &lt;div&gt; <br>      &lt;input type=&quot;text&quot; /&gt;<br>      &lt;input type=&quot;text&quot; ref={inputElRef}/&gt;<br>      &lt;input type=&quot;text&quot; /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>}<br>export default InputRef;`</pre><p><em>Just a side note here. We will have to access the </em><strong><em>ref </em></strong><em>using the </em><strong><em>current </em></strong><em>property which gives us access to current reference.</em></p><p><strong>Refs with react hooks</strong></p><p>To use Refs in React hooks we have a hook provided by React — <strong>useRef.</strong></p><pre>import React , { useEffect ,  useRef } from &#39;react&#39;</pre><pre>const inputRef = (props) =&gt; {</pre><pre> const inputElRef = useRef(null);<br> useEffect(() =&gt; {<br>  inputElRef.current.focus();<br> }, [])</pre><pre> return (<br>  &lt;div&gt;<br>   &lt;input type=&quot;text&quot; /&gt;<br>   &lt;input type=&quot;text&quot; ref={inputElRef}/&gt;<br>   &lt;input type=&quot;text&quot; /&gt;<br>  &lt;/div&gt;<br> )<br>}<br>export default inputRef;</pre><p>Side Note: We can pass an initial value in useRef to store any value, hence useRef is not just used to get access for the DOM element but we can store any other values as well. For this example, however, we pass null as an initial value.</p><h3>Now as we know how to create a ref we can talk about how to <strong>Forward a Ref.</strong></h3><p>Forwarding ref is a technique for automatically passing a ref through a component to one of its child components.</p><p>I’ll try to explain what forward Ref does through a basic use case.</p><p>Suppose we have a <strong>Navbar component</strong> and we have a <strong>Home Component</strong>. <br>Our Home Component has two sections viz “Our Services”, “Contact-Us”.<br>Navbar Component will have links to these Sections which when clicked will scroll us to that particular Section.</p><p>Now an easy and direct way for this is to pass the id of a section in href directly.</p><p>&lt;a href={&quot;#serviceId&quot;} &gt;Our Services&lt;/a&gt;</p><p><em>But to give you an example on how Forward ref work let’s pass on the id from Home Component to NavBar Component via our Parent Component. Looks a bit convoluting but it is damn easy!! :)</em></p><p>Now the typical React Structure will look something like this.<br>We will have a parent Layout/App Component which will have a component of Navbar and Home. (i.e Home and NavBar are children to Layout Component)</p><p>Now, this is how we will forward Refs:</p><p>Step 1: <strong>Create a ref for the Home Section in Parent Component (Layout). Pass all the refs as a single object.</strong></p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import NavBar from &#39;./components/NavBar/NavBar&#39;;<br>import Home from &#39;./components/Home/Home&#39;;</pre><pre>class App extends Component {</pre><pre>constructor(props) {<br>    super(props);<br>    this.homeRefService = React.createRef();<br>    this.homeRefContact = React.createRef();<br>  }</pre><pre>render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;NavBar /&gt;<br>        &lt;Home ref={{homeRefService: this.homeRefService, homeRefContact: this.homeRefContact }}/&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>    <br>}</pre><pre>export default App;</pre><p>Step 2: <strong>Forward this ref in Home Component using the dot forwardRef method from React Library.</strong></p><p><strong><em>The forward Ref method takes a component as its parameter</em></strong><em>. So we will have to pass the functional Home component as a parameter to forwardRef. Now every component receives “props ” as its parameter, but when we use forwardRef method, we can pass “ref” as a second parameter for that component. <br>It will be clear when we see the below code for Home Component.</em></p><pre>import React from &#39;react&#39;;</pre><pre>const home = React.forwardRef((props , ref) =&gt; {<br>    console.log(&#39;Ref&#39;, ref);<br>    return (<br>        &lt;div&gt;<br>            &lt;section&gt;<br>                Our Services<br>            &lt;/section&gt;</pre><pre>            &lt;section&gt;<br>                Contact Us<br>            &lt;/section&gt;<br>        &lt;/div&gt;<br>    )<br>})</pre><pre>export default home</pre><p>The output of console.log right now will be :</p><pre>{homeRefContact: {current: null}<br>homeRefService: {current: null}}</pre><p>We can then use Object Destructuring to get the refs for each section respectively and we pass the corresponding refs to each section.</p><pre>const { homeRefService , homeRefContact } = ref;</pre><pre>&lt;section ref={homeRefService} id=&quot;Services&quot;&gt; Our Services &lt;/section&gt;<br>&lt;section ref={homeRefContact}id=&quot;Contact&quot;&gt; Contact Us &lt;/section&gt;</pre><p>Once we pass these refs in each section on our Home Component, we will now have reference to these in our Parent Component (App / Layout).</p><p>Step 3<strong>: Since now we have the reference of sections present in the Home Component in our App Component (because of forward ref) we set the ref in state of App Component and then pass these refs as props to the NavBar component. Below is the code for App.js.</strong></p><pre>constructor(props) {<br>    super(props);<br>    this.homeRefService = React.createRef();<br>    this.homeRefContact = React.createRef();<br>    this.state = { homeServiceId: &quot;&quot;, homeContactId: &quot;&quot; }<br>  }</pre><pre>componentDidMount() {<br>    this.setState({<br>      homeServiceId: this.homeRefService.current.id,<br>      homeContactId: this.homeRefContact.current.id<br>    });<br>  }</pre><pre>render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;NavBar homeServiceId={this.state.homeServiceId} homeContactId={this.state.homeContactId}/&gt;<br>        &lt;Home ref={{homeRefService: this.homeRefService, homeRefContact: this.homeRefContact }}/&gt;<br>      &lt;/div&gt;<br>    );<br>  }</pre><p><em>A side note here:</em></p><p><em>The </em><strong><em>ref </em></strong><em>is only accessible when the component gets mounted to the DOM. So we will have to access the DOM element in </em><em>componentDidMount and hence we need to maintain a state in App.js for these refs.</em></p><p>Step 4: <strong>Finally we want to access the props in our NavBar component to get the id for these refs.</strong></p><pre>export class NavBar extends Component {<br>    render() {<br>        return (<br>            &lt;div&gt;<br>                &lt;a  href={&#39;#&#39; + this.props.homeServiceId}&gt; Our         Services&lt;/a&gt; <br>                &lt;a  href={&#39;#&#39; + this.props.homeContactId}&gt;Contact     Us&lt;/a&gt;<br>            &lt;/div&gt;<br>        )<br>    }<br>} </pre><p><em>If you need to implement this functionality, you can add a CSS property of<br></em>scroll-behavior: smooth; <em>and provide height to each section to check the scroll behavior.</em></p><h3><strong>Conclusion</strong></h3><p>We had a basic understanding of how ref actually works and how can we use forward ref. Using refs will definitely make our React code better as we will be more decisive in how we manage our state, props, and re-rendering. To read more about refs check out the docs<a href="https://reactjs.org/docs/refs-and-the-dom.html"> here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5bcb86fc69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/refs-and-forward-refs-in-react-be5bcb86fc69">Refs and Forward Refs in React.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>