<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: muhammadev</title>
    <description>The latest articles on DEV Community by muhammadev (@muhammadev).</description>
    <link>https://dev.to/muhammadev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F417036%2F0cc7378d-3849-4eef-91c0-dbf3eeaced18.jpeg</url>
      <title>DEV Community: muhammadev</title>
      <link>https://dev.to/muhammadev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muhammadev"/>
    <language>en</language>
    <item>
      <title>How to use React Context</title>
      <dc:creator>muhammadev</dc:creator>
      <pubDate>Mon, 12 Apr 2021 14:35:05 +0000</pubDate>
      <link>https://dev.to/muhammadev/how-to-use-react-context-59e0</link>
      <guid>https://dev.to/muhammadev/how-to-use-react-context-59e0</guid>
      <description>&lt;h3&gt;
  
  
  Prerequisite
&lt;/h3&gt;

&lt;p&gt;This article assumes you have a basic understanding of the React.js framework.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is Context?
&lt;/h3&gt;

&lt;p&gt;Context is the React solution for creating global data. This makes it consumable from any component, no matter how deep it is.&lt;/p&gt;

&lt;p&gt;The basic example of using Context. Assume you need to use the &lt;code&gt;theme&lt;/code&gt; state. And it's defined in the &lt;code&gt;App&lt;/code&gt; component, from the &lt;code&gt;GreatGrandChild&lt;/code&gt; component. To do that, you'll pass the state through each component in the components tree until you reach the &lt;code&gt;GreatGrandChild&lt;/code&gt; component.&lt;/p&gt;

&lt;p&gt;Context saves you that burden of prop drilling states and methods. Create a separate context file holding the state and its methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating A Context
&lt;/h3&gt;

&lt;p&gt;Creating a Context has 3 steps: creating, providing, and consuming. To create a Context create a file under the src directory of the project. It'll be named after the context's name such as &lt;code&gt;themeContext.js&lt;/code&gt;. Then use &lt;code&gt;createContext&lt;/code&gt; API which creates the Context object. Finally, export the context object.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;src/themeContext.js&lt;/em&gt; file&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  Providing A Context
&lt;/h3&gt;

&lt;p&gt;Each context object has a &lt;code&gt;Provider&lt;/code&gt; component. The &lt;code&gt;Provider&lt;/code&gt; component is used to provide the context to any of its children components. A &lt;code&gt;Provider&lt;/code&gt; component has a &lt;code&gt;value&lt;/code&gt; object prop which holds the context value and the updater method.&lt;/p&gt;

&lt;p&gt;Think of the Provider component as the house of the context. The components inside that house have access to it, so they can consume it and listen to its updates. So, whenever there is a change, all the consumer components are re-rendered.&lt;/p&gt;

&lt;p&gt;To make things easier, create the &lt;code&gt;Provider&lt;/code&gt; component inside the context file.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;src/themeContext.js&lt;/em&gt; file&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Now that we have the &lt;code&gt;Provider&lt;/code&gt; component, let's use it for providing the context. Import the &lt;code&gt;ThemeContextProvider&lt;/code&gt; component from inside &lt;em&gt;App.js&lt;/em&gt;. Then, pass the children components to it.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;src/App.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  Consuming A Context
&lt;/h3&gt;

&lt;p&gt;You have to tell React which component is dependent on the context. So that not every component is re-rendered on changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; There can be more than one provider in the components tree. The consumer components match the value of the nearest parent provider. If there are no providers above the consumer, it will receive the default value from the context file.&lt;/p&gt;

&lt;h4&gt;
  
  
  From class components
&lt;/h4&gt;

&lt;p&gt;To consume the context object from a class-based component, assign the context object to a static &lt;code&gt;contextType&lt;/code&gt; and you're good to go. This way you can destructure the &lt;code&gt;theme&lt;/code&gt; value and its updater from anywhere inside a component class.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;src/components/DeepLevelComponent.jsx&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Another way to consume a context from class-based components is to use the &lt;code&gt;themeContext.Consumer&lt;/code&gt; component but it's more of a legacy way. The trade-off here is that you can't use the Context value anywhere but inside the render method. On contrary, &lt;code&gt;contextType&lt;/code&gt; allows you to use the context in any lifecycle method besides the render method.&lt;/p&gt;

&lt;h4&gt;
  
  
  From functional components
&lt;/h4&gt;

&lt;p&gt;It's not very different. We'll use React hook &lt;code&gt;useContext&lt;/code&gt;. It does the same job as static &lt;code&gt;contextType&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;src/components/ChildComponent.jsx&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;Using context is easy and helpful. It could be what you're looking for, but be careful not to miss use it.&lt;/p&gt;

&lt;p&gt;That's it. I hope I clarified things enough. Feel free to write your thoughts in the comment section below.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Things I learned while trying to code an array shuffle</title>
      <dc:creator>muhammadev</dc:creator>
      <pubDate>Tue, 15 Sep 2020 05:36:16 +0000</pubDate>
      <link>https://dev.to/muhammadev/how-to-shuffle-arrays-3h41</link>
      <guid>https://dev.to/muhammadev/how-to-shuffle-arrays-3h41</guid>
      <description>&lt;p&gt;I was making a &lt;a href="https://codepen.io/Mohamed-tarek/full/mdPXEPm"&gt;memory game&lt;/a&gt;. I needed to shuffle the array of the answers. And I did something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = ["The Correct Answer", "Wrong Answer", "Wrong Answer"],
    result = [];

// pick random value, check that it's not picked before, push it to the result array
function randomUniqueValue(arr, result) {
  let index = Math.floor(Math.random() * arr.length);

  !result.includes(arr[index]) 
      ? result.push(arr[index])
      : randomUniqueValue(arr, result);
}

for (let i=0; i &amp;lt; arr.length; i++) {
  randomUniqueValue(arr, result);
}
console.log(result);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OK, This is &lt;strong&gt;WRONG!&lt;/strong&gt; If you care about performance, &lt;em&gt;and you should do&lt;/em&gt;, then this function is not for you.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why?
&lt;/h3&gt;

&lt;p&gt;At first, let's discuss what this function does. It declares a random &lt;strong&gt;&lt;code&gt;index&lt;/code&gt;&lt;/strong&gt; and check the value inside the given array. if the value has not picked before and pushed into the result array, then push it to the result array. If picked before, repeat.&lt;/p&gt;

&lt;h3&gt;
  
  
  But, what is wrong?
&lt;/h3&gt;

&lt;p&gt;Performance, my friend. This is the problem!&lt;br&gt;
While the result array is going bigger and bigger it makes the unpicked values less and less. thus the possibility of picking unpicked values lower and lower. Which means picking the already picked values over and over. which requires the function to repeat over and over. Big O notation!&lt;/p&gt;
&lt;h3&gt;
  
  
  Solution
&lt;/h3&gt;

&lt;p&gt;Geniuses statistical scientists, Ronald Fisher and Frank Yates, came up with this algorithm:&lt;br&gt;
why picking random indexes each time and losing time checking uniqueness?!&lt;br&gt;
We have to go for each value in the array and make it randomized ourselves!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1,2,3,4,5,6,7,8,9];

function shuffle() {
  let m = arr.length, i, t;

  while (m) {
    i = Math.floor(Math.random() * m--);

    t = arr[m];
    arr[m] = arr[i];
    arr[i] = t;
  }

  return arr;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way we don't care about the uniqueness of the picked index. we pick a random index and replace it with the last value of the array. then same thing with the value before the last, then the previous one, etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to measure the difference
&lt;/h3&gt;

&lt;p&gt;Copy each function into a code playground and console.log how many times the program picked an &lt;strong&gt;&lt;code&gt;index&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is what i got:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Q1zYqiie--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/e85l80s540mr3x21wurm.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Q1zYqiie--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/e85l80s540mr3x21wurm.jpg" alt="This is what i got:"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Look at the console, it took the while loop just 9 iterations, &lt;em&gt;the array length&lt;/em&gt;, to fully randomize the array.&lt;/p&gt;

&lt;p&gt;But, the &lt;em&gt;bad function&lt;/em&gt; gave me this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Brwau6gB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/q2lzokds18ym6uioxcvl.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Brwau6gB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/q2lzokds18ym6uioxcvl.jpg" alt="the *bad function*"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;37 iterations just to randomize 9 length array! and imagine the number's growth while the array length gets bigger!&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Your function can run without any bugs and do the job, but under the hood performance will suffer. So, it's always a good idea to search for the best algorithm to do somethings like shuffling arrays.&lt;/p&gt;

&lt;p&gt;But this does not mean that you shouldn't try to write an algorithm yourself! You should always try and get bugs to solve! This is how you learn and grow! And when you wrote the algorithm by yourself, go search for the best and compare. That will teach you what was wrong and how to avoid them in the future.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://bost.ocks.org/mike/shuffle/"&gt;Read more about Fisher-Yates shuffle&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>algorithms</category>
      <category>arrays</category>
    </item>
  </channel>
</rss>
