<?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>Forem: Kriti Rai</title>
    <description>The latest articles on Forem by Kriti Rai (@kritirai).</description>
    <link>https://forem.com/kritirai</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%2F48105%2F45270609-7031-4e4f-bc60-eedadf6fa189.png</url>
      <title>Forem: Kriti Rai</title>
      <link>https://forem.com/kritirai</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kritirai"/>
    <language>en</language>
    <item>
      <title>The Big O Notation</title>
      <dc:creator>Kriti Rai</dc:creator>
      <pubDate>Mon, 05 Aug 2019 20:35:04 +0000</pubDate>
      <link>https://forem.com/kritirai/the-big-o-notation-2cep</link>
      <guid>https://forem.com/kritirai/the-big-o-notation-2cep</guid>
      <description>&lt;p&gt;Let's say you have an array  and you need to come up with a function that checks if the array has a given number &lt;em&gt;n&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;You then write a simple function such as this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const linearSearch = (array, n) =&amp;gt; {
  for(let i = 0; i &amp;lt; array.length; i++) {
    if(array[i] == n) {
      return console.log(`${n} is at index ${i}`)
    }
  }
  return console.log(`${n} not found`);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;...and you are done or are you?&lt;/p&gt;

&lt;p&gt;Well, you might be in the best-case scenario where the given array is small enough and the function executes swiftly.&lt;/p&gt;

&lt;p&gt;But life ain't always that easy!&lt;/p&gt;

&lt;p&gt;What if the given array is huge? And, say, &lt;em&gt;n&lt;/em&gt; is not equal to the first element in the array but somewhere in the middle or not even there? The linear search function we wrote above still works but what about the execution time to go over each element in the array until it comes across the element we are looking for?  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z5_L-hpz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/nTXnixm.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z5_L-hpz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/nTXnixm.jpg" alt="source:imgur"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Make it work. Make it right. Make it fast!
&lt;/h2&gt;

&lt;p&gt;Following this cliched mantra for programmers, one should really consider the different scenarios -- the best, the worst and the acceptable one, before implementing algorithms.&lt;/p&gt;

&lt;p&gt;That's when the Big O comes into play.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6GbR1jjC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://media.makeameme.org/created/big-o.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6GbR1jjC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://media.makeameme.org/created/big-o.jpg" alt="makeameme.org"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Big O notation in Computer Science is used to explain how the runtime or the space used scales with respect to input variable(s) and is essential in understanding the efficiency of an algorithm. In this post, I will mostly focus on the time complexity so let's go over some common runtimes.&lt;/p&gt;

&lt;h2&gt;
  
  
  O(N) - Linear
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;O(N)&lt;/em&gt; describes the performance of an algorithm that scales linearly with the input size. Say, you have an array of 100 element. It would take 100 iterations through the loop to &lt;code&gt;console.log()&lt;/code&gt;  all the items. Similarly, with one million elements it would take one million iterations. Hence, the time complexity is directly proportional to the data input size.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ByWNanG8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/YrmiRlP.jpgg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ByWNanG8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/YrmiRlP.jpgg" alt="Fig 1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  O(1) - Constant Time Complexity
&lt;/h2&gt;

&lt;p&gt;With constant time complexity, the time taken to execute is constant regardless of the size of the data input. Let's say you have a  file to transfer over from one city to another. Normally, you'd attach the file to an email and send it over or decide to do a FTP transfer. In either case, the bigger the file size, the longer it would take for you to transfer the file over. Hence, the runtime would be linear, i.e. O(N).&lt;br&gt;
However, let's say you come up with an ingenious idea of transferring your gigantic file to a flash drive and sending it over to the recipient via a pigeon (because mailing is boring) that you trained to do so. Now, think about the relationship between the file size and the transfer time. Would it matter if the file was 1GB or 1TB? Our pigeon friend would still take the same amount of time to fly over and deliver the flash drive. So, here our runtime would be &lt;em&gt;O(1)&lt;/em&gt;, meaning our algorithm will always execute at the same time regardless of the size of the input data. In that case a pigeon would be faster than the internet.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xtIMHZPN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/T52TPgs.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xtIMHZPN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/T52TPgs.jpg" alt="Fig 2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It's not to say that O(1) is always better than O(N) or vice versa. It really depends on the size of the input variable. The figure below demonstrates how at some point O(N) algorithm will surpass the runtime of an O(1) algorithm, thereby making O(1) a better choice for data of the size that is greater than that which corresponds to the interception point. However, prior to the interception point, O(N) is more efficient.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--52ufgEM_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/UnUU7Pv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--52ufgEM_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/UnUU7Pv.jpg" alt="Fig 3"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  O(N^2) - Quadratic
&lt;/h2&gt;

&lt;p&gt;O(N^2) describes an algorithm whose performance is directly proportional to the square of the size of the input data set. This commonly involves nested iterations over the data set, like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1,2,3,4,5];

for(let i = 0; i &amp;lt; arr.length; i++) {
  for(let j = 0; j &amp;lt; arr.length; j++) {
    console.log(i +"" +j);
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Some other examples would be &lt;a href="https://www.geeksforgeeks.org/bubble-sort/"&gt;bubble sort&lt;/a&gt; and comparing elements in two arrays of the same size.&lt;/p&gt;

&lt;h2&gt;
  
  
  O(2^N)
&lt;/h2&gt;

&lt;p&gt;Another common runtime you might see is O(2^N). Algorithms with this runtime are often recursive algorithms that solve a problem of size &lt;em&gt;N&lt;/em&gt; by recursively solving two smaller problems of size &lt;em&gt;N-1&lt;/em&gt;. The growth curve of an O(2^N) function is exponential - starting off very shallow, then rising sharply.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1ULSX9tO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/odiNjyd.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1ULSX9tO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/odiNjyd.jpg" alt="Fig 4"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A good example of O(2^N) algorithm is the recursive calculation of Fibonacci number.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function calculateFibonacciNumber(N) {
  if (N &amp;lt;= 1) {
     return N;
  } else {
   return calculateFibonacciNumber(N - 2) + calculateFibonacciNumber(N - 1);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  O(logN) - Logarithmic
&lt;/h2&gt;

&lt;p&gt;With logarithmic notation execution time increases, but at a decreasing rate. Performing &lt;a href="https://en.wikipedia.org/wiki/Binary_search_algorithm"&gt;Binary Search&lt;/a&gt; on a sorted array is a good example of O(logN) runtime. Such algorithm traverses the input data once and then on every subsequent iteration the size of the input data is halved. Below is the growth curve depicting a logarithmic runtime. You can tell why Binary Search is a good choice when it comes to working with a large data.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Y0AXosio--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i1.wp.com/www.jenniferbland.com/wp-content/uploads/Olog-n-logarithmic-complexity.jpg%3Fw%3D472%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y0AXosio--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i1.wp.com/www.jenniferbland.com/wp-content/uploads/Olog-n-logarithmic-complexity.jpg%3Fw%3D472%26ssl%3D1" alt="Fig 5"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Note:
&lt;/h2&gt;

&lt;p&gt;There are couple of things to note while calculating Big O notation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1) Drop the constant and the non-dominant terms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Big O takes the worst case into consideration so we are trying to predict what happens to our algorithm's efficiency when the data input size is ridiculously big. In that sense, if N's value is ridiculously huge, any other constant compares almost non-existent to N. Hence, we drop the constants. So, O(2N) is simply O(N). Likewise, we also drop the non-dominant terms. For instance, O(N^2 + N) becomes O(N^2), O(N+logN) becomes O(N) and so on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2) Multiply v. Add&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If we do A chunks of work then B chunks of work, the total amount of work is O(A+B)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;arrayA.forEach(el =&amp;gt; console.log(el))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Similarly, if we do B chunks of work for each element in A, the total amount of work is O(AxB)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;arrayA.forEach ( a =&amp;gt; {
   arrayB.forEach ( b =&amp;gt; {
    console.log(a+" " + b);
   })
})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And, finally here's a graph I pulled from this &lt;a href="https://medium.com/@cindychen13.work/a-beginners-guide-to-big-o-notation-793d654973d"&gt;post&lt;/a&gt; showing how different runtimes compare.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lxPQ9IXa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/803Xb30.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lxPQ9IXa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/803Xb30.jpg" alt="Fig 6"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;If you are new to programming, Big O notation might not be your primary focus. However, as you embark on your journey to becoming an awesome programmer you will want to understand the complexities of your algorithms and how they will behave when the input size grows. This is the real world we are talking about and you never know what size of data you might have to work with. Hence, Big O lets us prepare ourselves for the worst-case scenarios, helping us make a sound decision when it comes to devising and implementing algorithms.&lt;/p&gt;

</description>
      <category>bigonotation</category>
      <category>algorithms</category>
      <category>programming</category>
    </item>
    <item>
      <title># State Hook in React</title>
      <dc:creator>Kriti Rai</dc:creator>
      <pubDate>Sun, 28 Jul 2019 00:46:35 +0000</pubDate>
      <link>https://forem.com/kritirai/state-hook-in-react-53c7</link>
      <guid>https://forem.com/kritirai/state-hook-in-react-53c7</guid>
      <description>&lt;p&gt;For some time we had been referring to function components as &lt;em&gt;stateless&lt;/em&gt; components and would have to write a &lt;code&gt;class&lt;/code&gt; every time we needed to make use of a local state. However, with the introduction of hooks in React 16.8, one can now use the inbuilt hook called &lt;code&gt;useState&lt;/code&gt; or otherwise called &lt;em&gt;State Hook&lt;/em&gt; that lets one add local state to function components.&lt;/p&gt;

&lt;p&gt;As per &lt;a href="https://reactjs.org/docs/hooks-state.html"&gt;React.js docs&lt;/a&gt;, &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;State Hooks are basically functions that let you ‘hook into’ React state and lifecycle features from function components&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s see how we can rewrite a class component using the state hook. Let's say we have a &lt;code&gt;Like&lt;/code&gt; component that renders the number of total likes as well as a like button and an unlike button. When  a user clicks on the like button the likes go up by 1 and conversely, when a user clicks on the unlike button the likes go down by 1. &lt;/p&gt;

&lt;p&gt;Since our component needs to remember the number of likes to be able to update and display it, it will need to make use of &lt;em&gt;state&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;Prior to the introduction of hooks we'd normally write a &lt;code&gt;class&lt;/code&gt; in order to use &lt;em&gt;state&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Like extends Component {
  constructor(props) {
    super(props);
    this.state = { likes: 0 }
  }

  handleLike = (e) =&amp;gt; {
    e.preventDefault();
    this.setState({ likes: this.state.likes + 1})
  }

  handleUnlike = (e) =&amp;gt; {
    e.preventDefault();
    this.state.likes &amp;gt; 0 ? this.setState({ likes: this.state.likes - 1}): null;
  }

  render () {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;h4&amp;gt;Likes: { this.state.likes }&amp;lt;/h4&amp;gt;
        &amp;lt;button style={{ backgroundColor: '#99ccff' }} onClick={ this.handleLike }&amp;gt; Like &amp;lt;/button&amp;gt;
        &amp;lt;button style={{ backgroundColor: 'red' }} onClick={ this.handleUnlike }&amp;gt; Unlike &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;

    )
  }
}

const el = &amp;lt;Like /&amp;gt;

ReactDOM.render(el, document.getElementById('root'));

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



&lt;p&gt;This would give us something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/JrYkYH2Jkyw58u9mJs/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/JrYkYH2Jkyw58u9mJs/giphy.gif" alt="gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we zero in on the snippet below, we see that we initialized the &lt;code&gt;likes&lt;/code&gt;  state to 0 with this line &lt;code&gt;this.state = { likes: 0 }&lt;/code&gt; in the constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt; constructor() {
    super();
    this.state = { likes: 0 }
  }

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



&lt;p&gt;Now, with state hooks we can re-write the code above using &lt;code&gt;useState&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Like() {
 const [likes, setLikes] = useState(0);
 ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  What’s happening here?
&lt;/h2&gt;

&lt;p&gt;First, we imported &lt;code&gt;useState&lt;/code&gt; from React. Then, we converted our class component to a function component &lt;code&gt;Like()&lt;/code&gt;. Finally, inside the function we have this one liner:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const [likes, setLikes] = useState(0);&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useState&lt;/code&gt; returns a pair of values -- the current state and a function that updates it. So, with the  &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring"&gt;array destructuring method&lt;/a&gt; we are declaring and assigning values to a state variable &lt;code&gt;likes&lt;/code&gt; and a function &lt;code&gt;setLikes&lt;/code&gt;, which is similar to &lt;code&gt;setState()&lt;/code&gt; method in a &lt;code&gt;class&lt;/code&gt;.  You can also see that &lt;code&gt;useState()&lt;/code&gt; takes in one argument which is the initial state of the component and that'd be  &lt;code&gt;0&lt;/code&gt; in this case as we haven't got likes from anyone yet :( &lt;/p&gt;

&lt;h2&gt;
  
  
  Updating State
&lt;/h2&gt;

&lt;p&gt;Since, we have our hands on &lt;code&gt;setLikes&lt;/code&gt; function that we declared above, we can now directly call the function to update the state. Let's re-write our handler functions &lt;code&gt;handleLike&lt;/code&gt; and &lt;code&gt;handleUnlike&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const handleLike = (e) =&amp;gt; {
    e.preventDefault();
    setLikes(likes + 1)
  }

  const handleUnlike = (e) =&amp;gt; {
    e.preventDefault();
    likes &amp;gt; 0 ? setLikes(likes - 1): null;
  }

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



&lt;p&gt;See, how we can easily call &lt;code&gt;setLikes&lt;/code&gt; to update our &lt;code&gt;likes&lt;/code&gt;? So, instead of writing &lt;code&gt;this.setState({ likes: this.state.likes + 1})&lt;/code&gt; like we'd do in our &lt;code&gt;class&lt;/code&gt; we can just write &lt;code&gt;setLikes(likes + 1)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's also update the &lt;code&gt;return&lt;/code&gt; value of our function by replacing &lt;code&gt;{ this.handleLike }&lt;/code&gt; and &lt;code&gt;{ this.handleUnlike }&lt;/code&gt; with just  &lt;code&gt;{ handleLike }&lt;/code&gt; and &lt;code&gt;{ handleUnlike }&lt;/code&gt; , respectively. Finally, here's our &lt;code&gt;Like&lt;/code&gt; component re-written using the state hook.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Like() {
  const [likes, setLikes] = useState(0);

  const handleUpClick = (e) =&amp;gt; {
    e.preventDefault();
    setLikes(likes + 1)
  }

  const handleDownClick = (e) =&amp;gt; {
    e.preventDefault();
    likes &amp;gt; 0 ? setLikes(likes - 1): null;
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h4&amp;gt;Likes: { likes }&amp;lt;/h4&amp;gt;
      &amp;lt;button style={{ backgroundColor: '#99ccff' }} onClick={ handleUpClick }&amp;gt; Like &amp;lt;/button&amp;gt;
      &amp;lt;button style={{ backgroundColor: 'red' }} onClick={ handleDownClick }&amp;gt; Unlike &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

const el = &amp;lt;Like /&amp;gt;

ReactDOM.render(el, document.getElementById('root'));

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



&lt;p&gt;So, here you go! With React hooks, function components can now have some state without you having to write those clunky classes. However, this does not mean that you have to go back and convert all your existing class components. And also, hooks are totally optional and there is no intent of them replacing classes. However, from now on you at least have the options to use hooks in case you need to use &lt;em&gt;state&lt;/em&gt; inside your function components. Note that hooks come with React 16.8, so if you want to use them make sure to upgrade React and ReactDOM. &lt;/p&gt;

</description>
      <category>react</category>
      <category>hooks</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Media Queries For Responsive Apps</title>
      <dc:creator>Kriti Rai</dc:creator>
      <pubDate>Mon, 20 May 2019 18:38:31 +0000</pubDate>
      <link>https://forem.com/kritirai/media-queries-for-responsive-apps-539p</link>
      <guid>https://forem.com/kritirai/media-queries-for-responsive-apps-539p</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--SbaxLI6y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/MCsEzZB.png%3F1" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SbaxLI6y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/MCsEzZB.png%3F1" alt="source:https://blog.hellojs.org/re-create-css-flexbox-media-queries-with-javascript-c192e4e16a63"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For our school projects we are not quite concerned about making our apps look pretty but rather meeting the requirements and hitting the core concepts. Eventually, though, you would and should want to deploy one or all of your apps to showcase your work. That is when  you might want to work on the way your app looks as this could be one such case where looks matter. So, I decided to work on deploying &lt;a href="https://github.com/kriti-rai/trailista"&gt;my app&lt;/a&gt;  that I built for the final project at Flatiron School - the first stop being its responsiveness.&lt;/p&gt;

&lt;p&gt;With the increasing variety of devices we use nowadays to access contents on the web, it makes sense to architect our app's design to adjust to varying media types, screen/viewport sizes and such, providing a good user-experience that we as developers strive for. I used Chrome's &lt;a href="https://developers.google.com/web/tools/chrome-devtools/device-mode/"&gt;Responsive Web Design Tester Tool&lt;/a&gt; to simulate different viewport dimensions of devices such as iPhone 5/SE, iPad and laptops, to get the idea of how my app looks on different screen sizes. However, everytime I switched between viewports other than a laptop's, I cringed at the way my app looked. For instance, on iPhone 5's viewport, my &lt;em&gt;search form&lt;/em&gt;  that otherwise so nicely stretched across the page now broke into two rows with the input boxes unattractively stacked on top of each other. The letters in the &lt;em&gt;navbar&lt;/em&gt; were gigantic in proportion to the viewport size, and my app just did not look neat and finished anymore. So, I decided to turn to media queries.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Media queries are powerful tools lent by CSS3 to alter the way the content of the app adjusts to the device type, viewport/screen size and orientation. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;These tools allow us to tell our program to apply certain CSS rules if the specific conditions are met. &lt;/p&gt;

&lt;p&gt;The basic syntax for media queries consist of the keyword &lt;code&gt;@media&lt;/code&gt; followed by &lt;em&gt;media type&lt;/em&gt; and expression(s).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@media &amp;lt; media-type &amp;gt; and (expression) {
     /* CSS rule for styling ...*/ 
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Media Types
&lt;/h2&gt;

&lt;p&gt;The available media types are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;all&lt;/code&gt; - includes all devices&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;print&lt;/code&gt; - used for displaying content in print-preview mode&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;screen&lt;/code&gt;  - includes mobile, tablet, and desktop devices&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;speech&lt;/code&gt; - intended for speech synthesizers
We are usually concerned with &lt;code&gt;screen&lt;/code&gt;. So, to target &lt;code&gt;screen&lt;/code&gt; media types we could write something like:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@media screen and (expression) {
/* CSS rule */
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Logical Operators
&lt;/h2&gt;

&lt;p&gt;Logical operators can be used to separate or combine more than one condition.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;and&lt;/code&gt; - Using &lt;code&gt;and&lt;/code&gt; requires media feature expressions on both sides of the keyword to return true in order for the media query to return true. It is also used to join media type with media features.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;or&lt;/code&gt; - Also, written as a &lt;em&gt;comma (,)&lt;/em&gt; only requires one of the comma-separated conditions to return true for the entire media statement to return true, thereby triggering the media query to apply.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;only&lt;/code&gt; - Requires the entire condition to match in order for CSS to apply. It comes in handy during situations where you want to hide media queries from older browsers and like &lt;code&gt;not&lt;/code&gt;, must come at the beginning of the declaration followed by media type.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;not&lt;/code&gt; - Negates a media query, returning true if the query would otherwise return false.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Expression
&lt;/h2&gt;

&lt;p&gt;We use this part of the code to target &lt;a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features"&gt;media features&lt;/a&gt;, such as &lt;em&gt;width&lt;/em&gt;, &lt;em&gt;height&lt;/em&gt;, &lt;em&gt;resolution&lt;/em&gt;, etc. &lt;br&gt;
For example, the query below will target the &lt;code&gt;width&lt;/code&gt; media feature and for any device with viewport width of 425px, the content inside &lt;code&gt;p&lt;/code&gt; tag will be red.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@media and screen and (width: 425px) {
    p {
     color: red;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We can also use &lt;code&gt;min-width&lt;/code&gt; and &lt;code&gt;max-width&lt;/code&gt; variants to query minimum and maximum values, respectively. For example, the query below will apply to any device with viewport &lt;code&gt;width&lt;/code&gt; between 0 and1024px.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@media screen and (max-width: 1024px) {
    p {
     color: blue;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And, &lt;em&gt;voila!!&lt;/em&gt; there you have a responsive app. Of course, you can build complex media queries depending on the complexity of your app but hopefully this basic knowledge of media queries will get you started on your journey to master building responsive web apps.&lt;/p&gt;

&lt;p&gt;Finally, here's a snippet of what my app looks like now in varying viewport sizes:&lt;br&gt;
&lt;a href="https://i.giphy.com/media/Ke9BSTFF7JsJj6DNZQ/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/Ke9BSTFF7JsJj6DNZQ/giphy.gif" alt="giphy"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>css</category>
      <category>frontend</category>
      <category>programming</category>
      <category>mediaqueries</category>
    </item>
    <item>
      <title>What is State in React?</title>
      <dc:creator>Kriti Rai</dc:creator>
      <pubDate>Fri, 03 May 2019 15:34:45 +0000</pubDate>
      <link>https://forem.com/kritirai/what-is-state-in-react-4im6</link>
      <guid>https://forem.com/kritirai/what-is-state-in-react-4im6</guid>
      <description>&lt;p&gt;In English, &lt;strong&gt;&lt;em&gt;state&lt;/em&gt;&lt;/strong&gt; refers to "the particular condition that someone or something is in at a specific time" and that holds true in React as well. State is basically a JavaScript object that stores a component's data that are prone to changes, enabling a component to keep track of the changing information in between renders. That's what makes components &lt;em&gt;reactive&lt;/em&gt; in nature. &lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Why&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you have a static app, &lt;strong&gt;don't use state&lt;/strong&gt;. However, if you want your app to be interactive, like for example a clock widget that shows and updates time at a set interval or an app where one can log in and out, add, delete and update resources - it will involve state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But, wait a minute don't we use props to store data in components?&lt;/strong&gt; Yes, but the crucial difference here is that &lt;em&gt;props&lt;/em&gt; are immutable (read-only) in that the components can not change their props as they are passed down from parent components. In contrast, component has a full control over its state and can modify it.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The How&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let's look at an example (inspired by the ticking clock example in &lt;a href="https://reactjs.org/docs/state-and-lifecycle.html"&gt;React docs&lt;/a&gt;) to see how &lt;em&gt;state&lt;/em&gt; works.&lt;/p&gt;

&lt;p&gt;We will build a  simple &lt;code&gt;Countdown&lt;/code&gt; component that renders the final countdown to the New Year's day.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HhUN4S4B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://i.pinimg.com/originals/1f/9f/43/1f9f43d0d06374e4bfbe441f2c2ab876.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HhUN4S4B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://i.pinimg.com/originals/1f/9f/43/1f9f43d0d06374e4bfbe441f2c2ab876.gif" alt="countdown_gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Keep in mind,&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;state&lt;/em&gt; is a feature only available in &lt;em&gt;classes&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, let's start by building an ES6 class for our component and write some pseudo code inside to show what it should do.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import ReactDOM from 'react-dom';

export default class Countdown extends React.Component {

 timer () {
 // some function that updates the  countdown
 }

 render () {
  return ( 
  // shows the countdown 10 through 1 and renders the message HAPPY NEW YEAR!!
  )
 }
}

const element = &amp;lt;Countdown /&amp;gt;

ReactDOM.render(element, document.getElementById('root'));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, in order to manipulate the state, you ought to have something to begin with, right? Yup, an &lt;strong&gt;initial state.&lt;/strong&gt; So, let's do that - let's  declare the initial state of the component and give it an attribute of &lt;code&gt;secondsLeft&lt;/code&gt;. We'll start with 10 &lt;code&gt;secondsLeft&lt;/code&gt; and do a countdown until it's 0 &lt;code&gt;secondsLeft&lt;/code&gt;. Now, where shall we declare the initial state? Constructor function it is! Because that's what fires before our component is mounted, making it the perfect candidate for setting up defaults including the initial state. Let's add the following block inside our component class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;constructor() {
  super();
  this.state = { secondsLeft: 10}
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Make sure to pass in &lt;code&gt;props&lt;/code&gt; as an argument to &lt;code&gt;constructor()&lt;/code&gt; and &lt;code&gt;super()&lt;/code&gt; if you wish to use &lt;code&gt;this.props&lt;/code&gt; within the class.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, let's work on our &lt;code&gt;timer()&lt;/code&gt; function that updates our component's state of &lt;code&gt;secondsLeft&lt;/code&gt; by subtracting 1 from it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;timer = () =&amp;gt; {
 if (this.state.secondsLeft &amp;gt; 0) {
  this.setState({ secondsLeft: this.state.secondsLeft - 1 })
 }
}

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



&lt;blockquote&gt;
&lt;p&gt;We use &lt;code&gt;this.setState()&lt;/code&gt; to update a component's state rather than doing something like &lt;code&gt;this.state = someValue&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Calling &lt;code&gt;this.setState()&lt;/code&gt; tells React that the component's state has updated and that the component needs to be re-rendered.&lt;/p&gt;

&lt;p&gt;Also, notice that I used an arrow function to define &lt;code&gt;timer&lt;/code&gt;. This is to bind the keyword &lt;code&gt;this&lt;/code&gt; to the instance of the component we are working with. &lt;/p&gt;

&lt;p&gt;Moving on, let's add a lifecycle method &lt;code&gt;componentDidMount()&lt;/code&gt; which will run after the component output has been rendered in the DOM. This is also a good place to call &lt;code&gt;timer()&lt;/code&gt;. So, starting with the initial state, with every second the state of the component updates as &lt;code&gt;timer()&lt;/code&gt; fires, thus re-rendering the component every second.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;componentDidMount() {
 setInterval(
  () =&amp;gt; this.timer(),
   1000
   );
 }

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



&lt;p&gt;Here's the final code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom';

export default class Countdown extends React.Component {
  constructor() {
    super();
    this.state = { secondsLeft: 10 }
  }

  componentDidMount() {
    setInterval(
      () =&amp;gt; this.timer(),
      1000
    );
  }

 timer = () =&amp;gt; {
  if (this.state.secondsLeft &amp;gt; 0) {
     this.setState({ secondsLeft: this.state.secondsLeft - 1 })
  }
 }

  render() {
    const message =  (this.state.secondsLeft === 0 )? &amp;lt;font color="red"&amp;gt;Happy New Year!!!&amp;lt;/font&amp;gt; : this.state.secondsLeft 
    return &amp;lt;h1&amp;gt;{ message }&amp;lt;/h1&amp;gt;
  }
}

const el = &amp;lt;Countdown  /&amp;gt;

ReactDOM.render(el, document.getElementById('root'));

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



&lt;h2&gt;
  
  
  &lt;strong&gt;...aaaaand Action!!&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/u0ag71wII1yBjMAOAc/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/u0ag71wII1yBjMAOAc/giphy.gif" alt="countdown_gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;&lt;em&gt;TL;DR&lt;/em&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;If you want interactive components use state&lt;/li&gt;
&lt;li&gt;State is a feature only available within class components&lt;/li&gt;
&lt;li&gt;React maintains state as an object which can be accessed through &lt;code&gt;this.state&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;State is similar to props, but is private and fully controlled by the component and can not be accessed and modified outside the component (&lt;em&gt;think encapsulation&lt;/em&gt;)&lt;/li&gt;
&lt;li&gt;Don't set the state directly like &lt;code&gt;this.state = someValue&lt;/code&gt; but use &lt;code&gt;this.setState()&lt;/code&gt; instead&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Resources:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/uberVU/react-guide/blob/master/props-vs-state.md"&gt;Props and State&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/docs/thinking-in-react.html"&gt;Thinking in React&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/docs/components-and-props.html"&gt;Components and Props&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/docs/state-and-lifecycle.html"&gt;State and Lifecycle&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>state</category>
      <category>webdev</category>
    </item>
    <item>
      <title>My React/Redux portfolio project</title>
      <dc:creator>Kriti Rai</dc:creator>
      <pubDate>Mon, 15 Apr 2019 18:26:10 +0000</pubDate>
      <link>https://forem.com/kritirai/my-react-redux-portfolio-project-2h4k</link>
      <guid>https://forem.com/kritirai/my-react-redux-portfolio-project-2h4k</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RwN2c0Ey--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/fla25b0.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RwN2c0Ey--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/fla25b0.jpg" alt="Trailista"&gt;&lt;/a&gt;&lt;br&gt;
For my final project for Flatiron's online fullstack programming course, I built an app called &lt;strong&gt;&lt;em&gt;&lt;a href="https://github.com/kriti-rai/trailista"&gt;Trailista&lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;, which pulls a list of trails from &lt;a href="https://www.hikingproject.com/data"&gt;Hiking Project Data API&lt;/a&gt; by location. You can watch a short demo of my app &lt;a href="https://www.youtube.com/watch?v=Tq6YfMEufpQ&amp;amp;t=1s"&gt;here&lt;/a&gt; or proceed to read as I briefly touch up on the setup and few roadblocks I came across during the process.&lt;/p&gt;

&lt;p&gt;This app is definitely a WIP but so far here are the available featues:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One can search for trails by city and country&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/lrbwszQmty9ybUdBQs/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/lrbwszQmty9ybUdBQs/giphy.gif" alt="search"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One can login or sign up&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/j0verhIyrSczORIdK0/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/j0verhIyrSczORIdK0/giphy.gif" alt="registration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;One can add trails to their favorites list and then delete them as they wish&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/mDXrTRqf6EMfTAyNat/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/mDXrTRqf6EMfTAyNat/giphy.gif" alt="favorites"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  The way it works
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;My app pulls trails from &lt;em&gt;Hiking Project API&lt;/em&gt; endpoint that looks something like this&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://www.hikingproject.com/data/get-trails?lat=40.0274&amp;amp;lon=-105.2519&amp;amp;maxDistance=10&amp;amp;key=APP_KEY"&gt;www.hikingproject.com/data/get-trails?lat=40.0274&amp;amp;lon=-105.2519&amp;amp;maxDistance=10&amp;amp;key=APP_KEY&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The client supplies the values for &lt;em&gt;lat&lt;/em&gt;, &lt;em&gt;lon&lt;/em&gt; and &lt;em&gt;maxDistance&lt;/em&gt; alongside a &lt;em&gt;key&lt;/em&gt; that is provided by &lt;em&gt;Hiking Project&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The app then takes the user inputs and plugs them into a &lt;code&gt;fetch&lt;/code&gt; request, and sends it to &lt;em&gt;Hiking Project&lt;/em&gt; API for a response back&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sounds pretty straightforward except that the user supplies the app with an address, e.g. a place's name, whereas &lt;em&gt;Hiking Project&lt;/em&gt; API endpoint wants the address in the form of GPS coordinates, i.e. the lattitude and the longitude. So I had to find a way to convert the location input to GPS coordinates. After rummaging through &lt;em&gt;Hiking Project&lt;/em&gt;' FAQs forum for some time, I  found a thread where someone had mentioned using &lt;em&gt;&lt;a href="https://docs.mapbox.com/api/search/#geocoding"&gt;MapBox&lt;/a&gt;&lt;/em&gt; to carry out, what they apparently call, "forward geo-coding", i.e. the process of converting an address to coordinates (the opposite would be &lt;em&gt;reverse geo-coding&lt;/em&gt;). I also looked into &lt;a href="https://developers.google.com/places/web-service/intro"&gt;Google maps API&lt;/a&gt; but apparently they charge? So, I decided to stick with MapBox.&lt;/p&gt;

&lt;p&gt;And, boy was this fun? Yes, it involved some hair-pulling episodes but I'm fairly proud of this part the way I got it working. My two functions, the heroes of my app, &lt;code&gt;getCoordinates()&lt;/code&gt; and &lt;code&gt;fetchHikes()&lt;/code&gt;, work in coordination to make this happen. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;getCoordinates()&lt;/code&gt;  takes the user input and sends a &lt;code&gt;fetch&lt;/code&gt; request to &lt;em&gt;MapBox&lt;/em&gt; API, like so:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getCoordinates= (e) =&amp;gt; { 
    e.preventDefault();
    axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${this.state.city}.json?country=${this.state.countryCode}&amp;amp;access_token=APP_KEY`)
      .then(resp =&amp;gt; {
        this.setState({
          longitude: resp.data.features[0].geometry.coordinates[0],
          latitude: resp.data.features[0].geometry.coordinates[1]
        })
                ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;The response data is then used to set the values of &lt;code&gt;longitude&lt;/code&gt; and &lt;code&gt;latitude&lt;/code&gt; in the state, which is then used to make a &lt;code&gt;fetch&lt;/code&gt; request to &lt;em&gt;Hiking Project's&lt;/em&gt; API via the dispatch action &lt;code&gt;fetchHikes()&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getCoordinates= (e) =&amp;gt; {
...
   this.props.fetchHikes(this.state.latitude, this.state.longitude, this.state.maxDistance, this.state.maxResults)
  })
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  The Set Up
&lt;/h2&gt;

&lt;p&gt;This &lt;a href="https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/"&gt;article&lt;/a&gt; does a great job of guiding one through setting up a React app with Rails API. I had a rough idea of what resources I will be working with so I started with my models and controllers first and then set up (API) routes (in &lt;em&gt;'/config/routes.rb'&lt;/em&gt;) to which I could send &lt;code&gt;fetch&lt;/code&gt; and/or &lt;code&gt;post&lt;/code&gt; request. &lt;/p&gt;
&lt;h3&gt;
  
  
  Important!
&lt;/h3&gt;

&lt;p&gt;One thing to look out for is your &lt;em&gt;CORS&lt;/em&gt; (Cross Origin Resource Sharing) set up. Since my front-end and back-end were running on different domains, I had to find a way to tell my back-end server that the requests my front-end was sending were not harmful. If you initially set up your Rails API with the command &lt;code&gt;$ rails new myapp --api&lt;/code&gt;, you get a &lt;code&gt;cors.rb&lt;/code&gt; file already set up and you will just have to uncomment the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#Gemfile

gem 'rack-cors'

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





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#app/config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:3000'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

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



&lt;p&gt;Once all this was taken care of, I then moved onto my &lt;em&gt;client&lt;/em&gt; side, i.e. the front-end part. Also, before pulling data from &lt;em&gt;Hiking Project&lt;/em&gt;, I created some seed data to test how the data is rendered on my front-end.&lt;/p&gt;

&lt;h3&gt;
  
  
  Routes
&lt;/h3&gt;

&lt;p&gt;I set up my routes in &lt;code&gt;App.js&lt;/code&gt;. One interesting thing I found on the internet was that I could create a helper &lt;code&gt;PrivateRoute&lt;/code&gt; to lock down a route if one is not logged in, like e.g. my '&lt;em&gt;/user&lt;/em&gt;' route. This &lt;a href="https://reacttraining.com/react-router/web/example/auth-workflow"&gt;article&lt;/a&gt; talks about how one can set up a &lt;code&gt;PrivateRoute&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Components
&lt;/h3&gt;

&lt;p&gt;I started with presentational components that were mostly stateless and had DOM markups. As I progressed further I ended up adding props, state, connecting to the store and so on, which all led me to think about dividing up my components based on their functionality - containers and presentational. Containers are concerned with &lt;em&gt;how things work&lt;/em&gt;, contain logic and the most of the times are stateful. The latter, on the other hand, are just "dumb" components that are concerned with &lt;em&gt;how things look&lt;/em&gt; and has no logic or knowledge of state whatsoever. &lt;/p&gt;

&lt;p&gt;However, as Dan Abramov points out in this &lt;a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0"&gt;article&lt;/a&gt;, this pattern should not be enforced as a hard rule and if there is no necessity. So, you may see that some of my components act as both container and presentational or some of my presentational components have logic inside them and are not purely presentational. &lt;/p&gt;

&lt;h3&gt;
  
  
  Reducers
&lt;/h3&gt;

&lt;p&gt;Speaking of separation of concerns, instead of having one giant reducer, I decided to have one reducer managing only one independent slice of the state.  So, I ended up with three reducers, &lt;code&gt;alertsReducer&lt;/code&gt;, &lt;code&gt;hikesReducer&lt;/code&gt; and &lt;code&gt;userReducer&lt;/code&gt;. All of these reducing functions are then combined into a single reducer, &lt;code&gt;rootReducer&lt;/code&gt;, using &lt;code&gt;combineReducers&lt;/code&gt; helper function provided by &lt;code&gt;redux&lt;/code&gt;. This reducer is what gets passed to &lt;code&gt;createStore&lt;/code&gt;. &lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;I had a lot of fun building this application. And, like with all other projects, this one came with frustration but I've learned that that's what makes the accomplishment at the end so much worthwhile. However, this is not over yet and I still want to keep working on the app, adding some  more features like comments, users being able to rate and create hikes and so on. For all I know, sky is the limit and there is always room for improvement. As of now, I'm happy that I'm ready for my final assessment. The journey has just begun! &lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>api</category>
      <category>rails</category>
    </item>
    <item>
      <title>Combining Reducers</title>
      <dc:creator>Kriti Rai</dc:creator>
      <pubDate>Thu, 14 Mar 2019 00:02:14 +0000</pubDate>
      <link>https://forem.com/kritirai/combining-reducers-9la</link>
      <guid>https://forem.com/kritirai/combining-reducers-9la</guid>
      <description>&lt;p&gt;I was recently working on a &lt;a href="https://github.com/learn-co-students/crud-lab-v-000" rel="noopener noreferrer"&gt;lab&lt;/a&gt; in building a &lt;a href="https://www.yelp.com/" rel="noopener noreferrer"&gt;Yelp&lt;/a&gt;-like application that uses &lt;a href="https://reactjs.org/" rel="noopener noreferrer"&gt;React&lt;/a&gt; and &lt;a href="https://redux.js.org/" rel="noopener noreferrer"&gt;Redux&lt;/a&gt; to add and delete restaurants and  their reviews. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffs2ftvpdabd06kl23va.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffs2ftvpdabd06kl23va.gif" alt="app gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While working my way through the lab I found that my reducer function, &lt;code&gt;manageRestaurants&lt;/code&gt;, was dense. So, I naturally sought to split my giant reducer function into two children reducer functions so that each function was responsible for only one resource's state. Using &lt;a href="https://github.com/reduxjs/redux/blob/master/docs/api/combineReducers.md" rel="noopener noreferrer"&gt;combineReducers&lt;/a&gt;, I then combined the children reducers in one parent reducer function, &lt;code&gt;rootReducer&lt;/code&gt;, which is what gets passed to the &lt;a href="https://redux.js.org/api/store" rel="noopener noreferrer"&gt;store&lt;/a&gt;. This not only made my code cleaner but also much easier to debug.&lt;/p&gt;

&lt;p&gt;Finally, I got the app working in the browser just as the lab wanted and before I could take that big sigh of relief I found that the tests were failing. The lab just wanted us to create one reducer function and put all reducer logic in there. Ugh!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu583vsgahuale8ik1ecd.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu583vsgahuale8ik1ecd.gif" alt="office space"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Regardless, I decided to create a separate &lt;a href="https://github.com/kriti-rai/crud-lab-v-000/tree/combine-reducers" rel="noopener noreferrer"&gt;branch&lt;/a&gt; and push up my clean and amazing code there and reverted my &lt;code&gt;master&lt;/code&gt; branch to the old way to pass the tests. In so doing, however, I realized that now I had a greater understanding of how &lt;code&gt;combineReducers&lt;/code&gt; works. Additionally, now that I had seen both scenarios I could use that knowledge and experience to decide when I could use &lt;code&gt;combineReducers&lt;/code&gt;. If you are just working with one or two resources, maybe you don't quite need to use this helper function. However, imagine a big app with multiple resources and soon enough you will find yourself tangled up in a number of &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch" rel="noopener noreferrer"&gt;switch&lt;/a&gt; statements and a big, fat state with multiple key-value pairs.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Refactoring with combineReducers
&lt;/h2&gt;

&lt;p&gt;All talks aside, lets look at my giant reducer &lt;code&gt;manageRestaurants&lt;/code&gt; first, which is maintaining the state of both restaurants and reviews. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzdbqehx8wywjryc9e3gl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzdbqehx8wywjryc9e3gl.png" alt="reducer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let's split our giant reducer into two child reducer functions, say &lt;code&gt;restaurantReducer&lt;/code&gt; and &lt;code&gt;reviewReducer&lt;/code&gt;. The former manages the state of the restaurants whereas the latter manages the state of the reviews. &lt;/p&gt;

&lt;h3&gt;
  
  
  restaurantReducer
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdha408kdmqit3c5y14q4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdha408kdmqit3c5y14q4.png" alt="restaurantReducer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  reviewReducer
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8k9pjuxs29v5dak3jcjc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8k9pjuxs29v5dak3jcjc.png" alt="reviewReducer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now,  here's our &lt;code&gt;rootReducer&lt;/code&gt;, where we will call our children reducer functions. Notice, we imported &lt;code&gt;combineReducers&lt;/code&gt; from &lt;code&gt;redux&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  rootReducer
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft90y9pf9ahnz9qrcn2ou.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft90y9pf9ahnz9qrcn2ou.png" alt="rootReducers"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is equivalent to writing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function rootReducer(state = {}, action) {
  return {
    restaurants: restaurantReducer(state.restaurants, action),
    reviews: reviewReducer(state.reviews, action),
  };
};

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

&lt;/div&gt;



&lt;p&gt;This basically produces the same giant reducer function as &lt;code&gt;manageRestaurants&lt;/code&gt; does but in a much more abstract and cleaner way. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;If your app is big and has more than one or two resources, you might be better off splitting up the state object into slices and using a separate child reducer to operate on each slice of the state. The slices of state can then be combined using &lt;code&gt;combineReducers&lt;/code&gt;, a helper utility lent by &lt;em&gt;Redux&lt;/em&gt;, in a parent reducer, conventionally named &lt;code&gt;rootReducer&lt;/code&gt;.  Keep in mind that using &lt;code&gt;combineReducer&lt;/code&gt; might not be helpful if one is intending to learn what is going under the hood as it abstracts the way reducers are being combined and working together. So, try to play around with both scenarios to get a better understanding of how reducers work and when to use &lt;code&gt;combineReducers&lt;/code&gt;.&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
      <category>reducers</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
