<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Soham De Roy - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Soham De Roy - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:30:00 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/sohamderoy/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What is Tailwind CSS? A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Writing CSS can be really difficult. Period. And I get it – it can be frustrating to nail down your own ideas or the designs you get from your design team.  I'm sure many of you have gone through the same pain at least a few times in your ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-tailwind-css-a-beginners-guide/</link>
                <guid isPermaLink="false">66ba5d4b4b814a3715945384</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tailwind ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Design ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham De Roy ]]>
                </dc:creator>
                <pubDate>Mon, 12 Sep 2022 15:38:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/Group-69.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Writing CSS can be really difficult. Period. And I get it – it can be frustrating to nail down your own ideas or the designs you get from your design team. </p>
<p>I'm sure many of you have gone through the same pain at least a few times in your development careers. </p>
<p>Well not anymore. Because it's time to learn an interesting tool that takes away a lot of the burden from us. And no it's not Bootstrap – it's called Tailwind CSS. </p>
<p>While Tailwind has been around for a while now, you may not have come across it yet. Perhaps you just haven't heard about it, or you don't really know whether learning a new piece of tech related to CSS will really make your life easier. </p>
<p>And indeed there are a lot of ways to write CSS out there – like Vanilla CSS3, LESS, SCSS, Bootstrap, styled-components, Windi CSS, and more...phew. Quite a list isn't it?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/spongebob-long-list.gif" alt="spongebob-long-list" width="600" height="400" loading="lazy"></p>
<p>I hope this short guide will help you understand Tailwind CSS and its benefits so that you can say "This is it. This is the one".</p>
<p>Well enough of the chit chat. Let's dive straight in.</p>
<h2 id="heading-what-is-atomic-css">What is Atomic CSS?</h2>
<p>Before jumping into Tailwind CSS, let's understand what Atomic CSS is. According to <a target="_blank" href="https://css-tricks.com/lets-define-exactly-atomic-css/">CSS Tricks</a> </p>
<blockquote>
<p>"Atomic CSS is the approach to CSS architecture that favours small, single-purpose classes with names based on visual function." </p>
</blockquote>
<p>It's kinda like making classes that are supposed to achieve a single purpose. For example, let's make a <code>bg-blue</code> class with the following CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.bg-blue</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">81</span>, <span class="hljs-number">191</span>, <span class="hljs-number">255</span>);
}
</code></pre>
<p>Now if we add this class to a <code>&lt;h1&gt;</code> tag, it will get a background of blue with the colour being <code>rgb(81, 191, 255)</code> as you can see in the code above.</p>
<p>And here's the HTML:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-blue"</span>&gt;</span>Hello world!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>So this HTML will result in something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img2-1.PNG" alt="img2-1" width="600" height="400" loading="lazy"></p>
<p>Now imagine writing such useful <strong>single-purpose CSS rules</strong> and keeping them all in a <strong>global CSS file</strong>. I know it's a one-time investment but think of this – you can now use these single-purpose helper classes from anywhere you want. </p>
<p>You just need your HTML file to consume that global CSS file, and that's it. You can now also use combinations of these helper classes in a single HTML tag. </p>
<p>Let's see another example shall we?</p>
<p>Let's create a CSS file with the following rules:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.bg-blue</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">81</span>, <span class="hljs-number">191</span>, <span class="hljs-number">255</span>);
}
<span class="hljs-selector-class">.bg-green</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">81</span>, <span class="hljs-number">255</span>, <span class="hljs-number">90</span>);
}
<span class="hljs-selector-class">.text-underline</span> {
  <span class="hljs-attribute">text-decoration</span>: underline;
}
<span class="hljs-selector-class">.text-center</span> {
  <span class="hljs-attribute">text-align</span>: center;
}
<span class="hljs-selector-class">.font-weight-400</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">400</span>;
}
</code></pre>
<p>and then consume it in our HTML file as follows:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-blue"</span>&gt;</span>Hello world 1<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-underline"</span>&gt;</span>Hello world 2<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-green font-weight-400 text-underline"</span>&gt;</span>Hello world 3<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Well now this will generate the following result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img3-1.PNG" alt="img3-1" width="600" height="400" loading="lazy"></p>
<h3 id="heading-points-to-note-here">🗒️ Points to note here:</h3>
<ul>
<li><strong>Combining multiple helper classes:</strong> Look how I have combined multiple helper classes in line 14 in the <code>&lt;h1&gt;</code> tag, namely <code>bg-green</code>, <code>font-weight-400</code> and <code>text-underline</code>. It all took effect in my <strong>Hello world 3</strong> text.</li>
<li><strong>Reusability of helper classes:</strong> In the above example look at how the <code>text-underline</code> helper class is used multiple times in lines 12 and 14.</li>
</ul>
<p>See how we were able to add different styles without even leaving the HTML page. Well, you might say, "Hey we did have to write those helper or utility classes in the global CSS file... what about that?" Well, I get it. That definitely was the initial investment we had to make to start with. </p>
<p>And of course, who knows how many of these single-purpose helper or utility classes we would have to make if we wanted to follow this <em>Atomic CSS</em> architecture. </p>
<p>And that's where Tailwind CSS comes in. The concept of Atomic CSS is not new but Tailwind CSS takes it to another level.</p>
<h2 id="heading-tailwind-css-a-utility-first-css-framework">Tailwind CSS – A Utility First CSS Framework</h2>
<p>Tailwind CSS, as per their own <a target="_blank" href="https://tailwindcss.com/">website</a> is a "utility-first CSS framework" which provides several of these <strong>opinionated</strong>, <strong>single-purpose utility classes</strong> that you can use directly inside your markup to design an element. </p>
<p>Some of the utility classes that I frequently use these days are:</p>
<ul>
<li><strong>flex</strong>: Used to apply Flexbox to a <code>&lt;div&gt;</code></li>
<li><strong>items-center</strong>: to apply the CSS property <code>align-items: center;</code> to a <code>&lt;div&gt;</code></li>
<li><strong>rounded-full</strong>: to make an image circular, and so on </li>
</ul>
<p>Seriously, it's not possible for me to list all of them because there are so many of these utility classes. But the best part is, we do not have to write these utility classes ourselves and keep them in any global CSS file. We directly get them from Tailwind. </p>
<p>You can get a list of all the utility classes Tailwind has to offer from the <a target="_blank" href="https://tailwindcss.com/docs/installation">documentation page</a>. Also if you are working in VS Code, you can install an extension called <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss">Tailwind CSS IntelliSense</a> and it will give you auto-suggestions as you keep typing the utility classes, as shown in the image below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img4-1.PNG" alt="img4-1" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-set-up-tailwind-css">How to Set Up Tailwind CSS</h3>
<p>There are multiple ways you can set up Tailwind CSS in your project, all of which are mentioned in their <a target="_blank" href="https://tailwindcss.com/docs/installation">documentation</a>. </p>
<p>Tailwind CSS works smoothly with a plethora of frameworks like Next, React, Angular, and more – and even our OG HTML. </p>
<p>For the below hands-on demo I am using <strong>Tailwind CSS with a Next application</strong>. To set up a Next app with Tailwind CSS directly, use the following command:</p>
<p>With <code>npx</code></p>
<pre><code class="lang-shell">npx create-next-app --example with-tailwindcss with-tailwindcss-app
</code></pre>
<p>or with <code>yarn</code></p>
<pre><code class="lang-shell">yarn create next-app --example with-tailwindcss with-tailwindcss-app
</code></pre>
<p>Once the project has been set up, you can dive into the next step to create a basic card component </p>
<h3 id="heading-hands-on-demo">Hands-on Demo</h3>
<p>Let's build a card component in a Next project.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Card.js file</span>
<span class="hljs-comment">// to be rendered in index.js</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Card = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"relative w-96 m-3 cursor-pointer border-2 shadow-lg rounded-xl items-center"</span>&gt;</span>
      {/* Image */}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex h-28 bg-blue-700 rounded-xl items-center justify-center"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"absolute mx-auto text-center right text-2xl text-white"</span>&gt;</span>
          Image goes here
        <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      {/* Description */}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"p-2 border-b-2"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h6</span>&gt;</span>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis
          beatae nulla, atque et sunt ad voluptatum quidem impedit numquam quia?
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis
          beatae nulla, atque et sunt ad voluptatum quidem impedit numquam quia?
        <span class="hljs-tag">&lt;/<span class="hljs-name">h6</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      {/* Tech stack used */}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-wrap items-center m-2"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">" border border-blue-300 rounded-2xl px-2 my-1 mx-1"</span>&gt;</span>
          #React
        <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">" border border-blue-300 rounded-2xl px-2 my-1 mx-1"</span>&gt;</span>
          #Redux
        <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">" border border-blue-300 rounded-2xl px-2 my-1 mx-1"</span>&gt;</span>
          #Javascript
        <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      {/* Links */}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-wrap items-center rounded-b-xl border-t-2 bg-white"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"border rounded-2xl bg-blue-600 text-white shadow-sm p-1 px-2 m-2"</span>&gt;</span>
          Go to Project
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"border-2 border-blue-600 rounded-2xl text-blue-600 shadow-sm p-1 px-2 m-2"</span>&gt;</span>
          Github
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Card;
</code></pre>
<p>This results in the following card that gets rendered in the UI:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img5-1.PNG" alt="img5-1" width="600" height="400" loading="lazy"></p>
<p>Look how easily I am able to style the card component without even leaving the Card.js file. No need to write any extra CSS files. </p>
<p>Using <code>flex</code> with a <code>&lt;div&gt;</code> applies <code>display: flex;</code> CSS rule to it. Want to add <code>position: relative;</code> to a <code>&lt;div&gt;</code>? Just add <code>relative</code> in the <code>className</code> and you are done.  </p>
<p>We can also add different modifiers like <code>hover</code>, <code>active</code>, <code>focus</code> and so on to conditionally render utility classes. It is possible to apply complex CSS rules like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.some-class-name</span> {
          <span class="hljs-attribute">--tw-space-x-reverse</span>: <span class="hljs-number">0</span>;
          <span class="hljs-attribute">margin-right</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">0.5rem</span> * var(--tw-space-x-reverse));
          <span class="hljs-attribute">margin-left</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">0.5rem</span> * calc(<span class="hljs-number">1</span> - var(--tw-space-x-reverse)));
}
</code></pre>
<p>by just mentioning <code>space-x-2</code> in the <code>&lt;div&gt;</code> tag. Neat, isn't it?</p>
<p>And do we have to mention these styles explicitly anywhere in some sort of a global CSS file? Absolutely not! Tailwind automagically does it for us. That's the beauty of Tailwind.</p>
<p>We are not done yet... there's a lot of other advantages. Let's look at them now.</p>
<h3 id="heading-advantages-of-tailwind-css">Advantages of Tailwind CSS</h3>
<h4 id="heading-just-in-time-jit-mode-provides-lightning-fast-build-times">Just-In-Time (JIT) mode provides lightning-fast build times</h4>
<p>Prior to Tailwind v3, it used to purge through all the styles to remove any unused styles, so that the production build remained as small as possible. </p>
<p>According to Tailwind, the production build used to be between 5-10 kB. But that's the story in production. In a development environment, CSS might get really big especially if we use a lot of personalized configuration.</p>
<p>With v3 and above, Tailwind released a new feature called the <strong>Just-in-Time compiler</strong>. The JIT compiler avoids compiling all the CSS upfront and compiles only the CSS as and when we need it. </p>
<p>This results in lightning-fast build times in all the environments. And as the styles are generated as and when we need them, there is no need to purge unused styles. This means that the CSS in all the environments will be the same. This helps us get rid of the fear of any important CSS getting purged in production.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/3O_3X7InOw8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h4 id="heading-its-opinionated-and-flexible-at-the-same-time">It's opinionated and flexible at the same time</h4>
<p>Tailwind CSS is opinionated. It does specify some constraints when it comes to styling, and if you ask me this is good as it helps us keep the design part to those who actually understand it. </p>
<p>Just look at one of the utility classes to add a <code>box-shadow</code> to your <code>&lt;div&gt;</code> (<a target="_blank" href="tailwindcss.com/docs/box-shadow">source</a>):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img6-1.PNG" alt="img6-1" width="600" height="400" loading="lazy"></p>
<p>As you can see, there are only 8 variants of shadow that Tailwind provides. There are preset values for vertical and horizontal offset, blur, spread, colour and opacity. That is why Tailwind is opinionated. </p>
<p>It tries to give an opinion about what property values to choose from on almost all the styling properties out there. And believe me, for most of the cases, these 8 variants (for <code>box-shadow</code>) will be more than sufficient to come up with a great UI. </p>
<p>For example in the above hands-on example, I have used <code>shadow-lg</code> in the main parent <code>&lt;div&gt;</code> to get that nice outer box-shadow. </p>
<p>Using the same variant of a particular utility class at different areas in the UI also ensures uniformity across the whole application and results in a better UX.</p>
<p>But in case you need some really customised value for any particular style, you can get that by adding a customized theme in the <code>tailwind.config.js</code>. For example to get a <code>shadow-3xl</code> (Tailwind does not provide <code>shadow-3xl</code> out of the box) you can add the following lines in the <code>module.exports</code> in <code>tailwind.config.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">theme</span>: {
    <span class="hljs-attr">extend</span>: {
      <span class="hljs-attr">boxShadow</span>: {
        <span class="hljs-string">'3xl'</span>: <span class="hljs-string">'0 35px 60px -15px rgba(0, 0, 0, 0.3)'</span>,
      }
    }
  }
}
</code></pre>
<p>And now with the advent of JIT, you can also use an arbitrary value inside square brackets <code>[]</code> like the following:</p>
<pre><code class="lang-jsx">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"shadow-[0_35px_60px_-15px_rgba(0,0,0,0.3)]"</span>&gt;
  <span class="hljs-comment">// Rest of your code goes here</span>
&lt;/div&gt;
</code></pre>
<p>Using arbitrary values may be useful when you need a specific style at only a few places. And in this case, creating a theme for it in the <code>tailwind.config.js</code> might seem unnecessary.</p>
<h2 id="heading-my-thoughts">My Thoughts</h2>
<p>I really hope that I was able to make you understand what Tailwind CSS is and what you can do with it. </p>
<p>Tailwind is a CSS framework that provides us with <strong>single-purpose utility classes</strong> which are <strong>opinionated</strong> for the most part, and which help us design our web pages from right inside our markup or .js/.jsx/.ts/.tsx files. </p>
<p>In my opinion, Tailwind is simple and easy to understand. It's true that it might take some time to get the hang of all the utility class names, but don't worry – you can refer to their documentation whenever you get stuck. </p>
<p>And to all the beginners out there who are just starting their journey with web development, it is very important to know what CSS3 is before you even explore Tailwind (or for that matter any other CSS framework like Bootstrap, Windi CSS, and so on). </p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Thanks for reading! I really hope you enjoyed reading about Tailwind CSS in this article and found it useful. </p>
<p>Do consider sharing it with your friends, I'd really appreciate that. Follow me on LinkedIn and Twitter (see below) and stay tuned for more amazing content. Peace out! 🖖</p>
<h2 id="heading-social-links">Social Links</h2>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/feed/">LinkedIn</a></li>
<li><a target="_blank" href="https://www.sohamderoy.dev/">Website</a></li>
<li><a target="_blank" href="https://blogs.sohamderoy.dev">Other Blogs by me</a></li>
<li><a target="_blank" href="https://twitter.com/_sohamderoy">Twitter</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Google like a Pro – 10 Tips for More Effective Googling ]]>
                </title>
                <description>
                    <![CDATA[ Pretty much everything is available on the internet, and Google is one of the main ways people search for information.  And while you might think it's obvious, many internet users don't know how to use Google search efficiently and effectively. In tr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-google-like-a-pro-10-tips-for-effective-googling/</link>
                <guid isPermaLink="false">66ba5d46e5ad5bacb410af20</guid>
                
                    <category>
                        <![CDATA[ Google ]]>
                    </category>
                
                    <category>
                        <![CDATA[ research ]]>
                    </category>
                
                    <category>
                        <![CDATA[ search ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham De Roy ]]>
                </dc:creator>
                <pubDate>Fri, 12 Aug 2022 18:19:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/Group-61.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Pretty much everything is available on the internet, and Google is one of the main ways people search for information. </p>
<p>And while you might think it's obvious, many internet users don't know how to use Google search <strong>efficiently</strong> and <strong>effectively</strong>.</p>
<p>In truth, Googling is an art. </p>
<p>To get the right answers, you need to ask the right questions. And to get the right answers quickly, you must know <strong>how</strong> to ask the right questions. </p>
<p>Everyone should learn the <strong>how</strong> part, and that's what this tutorial is all about. Below are some helpful tips and tricks you can use to find correct answers to your questions effectively and efficiently.</p>
<h2 id="heading-how-to-search-google-effectively">How to Search Google Effectively</h2>
<h3 id="heading-1-use-quotes-to-get-an-exact-match">1. Use quotes to get an "EXACT" match</h3>
<p>Generally, when we do a regular search on Google, it makes a <strong>shallow</strong> search. This may result in pages that may or may not contain all the words you mentioned in your search query. </p>
<p>But if you wrap your search query or question (either a term or a phrase) in quotes like this: <code>"your question goes here"</code> then Google will do a deep search. This means that all the results will include pages that <strong>contain all the terms</strong> in your question that you put within quotes. </p>
<p>This is helpful when you absolutely want a particular term or phrase to be there in your search results.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img1.PNG" alt="img1" width="600" height="400" loading="lazy"></p>
<h3 id="heading-2-search-within-a-specific-site-with-site">2. Search within a specific site with <code>site:</code></h3>
<p>If you want Google to return results from within a particular website, just add <code>site:</code> before the question you are searching. </p>
<p>This is also helpful when you want to search for something within a website that doesn't have an internal search option or perhaps doesn't have a very effective one. </p>
<p>For example, searching for <strong>site:freecodecamp.org react</strong> will populate search results only from the <a target="_blank" href="https://www.freecodecamp.org/">www.freecodecamp.org</a> website on the topic of React.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img2.PNG" alt="img2" width="600" height="400" loading="lazy"></p>
<h3 id="heading-3-exclude-a-term-from-search-results-with">3. Exclude a term from search results with <code>-</code></h3>
<p>If you don't want a term or phrase to appear in your search results, then just add <code>-</code> in front of that word. </p>
<p>For e.g. a search on =&gt; <strong>how to write components in React -class</strong> will return all the search results that don't have the term "class" in them. So, (if you know a bit of React) it'll give you only ways to write functional components in React.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img3.PNG" alt="img3" width="600" height="400" loading="lazy"></p>
<h3 id="heading-4-search-images-of-a-particular-size-with-imagesize">4. Search images of a particular size with <code>imagesize:</code></h3>
<p>If you want to search images of a particular size, then use the tag <code>imagesize:</code> in your search query along with the width and height in <strong>pixels</strong>. </p>
<p>Dimension should be in <strong>pixels</strong> only – for example, <code>imagesize:500x500</code> will populate image results which have a dimension of 500px x 500px. So a search on =&gt; "cute dog images imagesize:500x600" (coz why not) will result in pictures of cute dogs with an image size of <code>500px x 600px</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img4.PNG" alt="img4" width="600" height="400" loading="lazy"></p>
<h3 id="heading-5-search-for-a-particular-filetype-with-filetype">5. Search for a particular filetype with <code>filetype:</code></h3>
<p>If you want to get search results that contain a particular file type such as PDF or PPT, then add <code>filetype:&lt;extension&gt;</code> (without the angular brackets). For example, <strong>react tutorial filetype:pdf</strong> will generate results that contains PDF in them, as seen in the following image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img5.PNG" alt="img5" width="600" height="400" loading="lazy"></p>
<h3 id="heading-6-use-wildcard-to-make-searches">6. Use wildcard <code>*</code> to make searches</h3>
<p>If you are unsure about or have forgotten any term in your search query/ question, then use the wildcard <code>*</code> charachter. Google will replace it for you with relevant terms. </p>
<p>For example, a search on =&gt; the <em> of money will populate the following results. It will be a bunch of pages that include the phrase such as "the </em>exchange<em> of money", "the </em>use<em> of money", "the </em>role<em> of money", "the </em>psychology* of money", and so on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img6.PNG" alt="img6" width="600" height="400" loading="lazy"></p>
<h3 id="heading-7-combine-searches-with-or-and-logic">7. Combine searches with <code>OR</code>, <code>AND</code> logic</h3>
<p>If you want your search results to contain two terms, then put the <code>AND</code> keyword in between them. For example, the search on =&gt; <strong>React AND Angular</strong> will fetch results that have both the terms react and angular in it. </p>
<p>Similarly, if you want either of the terms in your search results, then use the <code>OR</code> keyword in between them. For example, the search on =&gt; <strong>React OR Angular</strong> will fetch results that have either of the terms or even both.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img7.PNG" alt="img7" width="600" height="400" loading="lazy"></p>
<h3 id="heading-8-filter-out-searches-with-after-before-or-between-two-numbers">8. Filter out searches with <code>AFTER:</code>, <code>BEFORE:</code> or <code>..</code> between two numbers</h3>
<p>If you want Google to populate search results that were published after a particular year, then use the tag <code>AFTER:</code>. For example, the search on =&gt; <strong>React tutorials AFTER:2020</strong> will populate search results published after 2020. </p>
<p>Similarly adding the tag <code>BEFORE:</code> will return results published before a particular year. </p>
<p>You can also search for results published in a certain year range, or for that matter between any numbers. Just add <code>..</code> between the two numbers you want to search between along with the units, if any.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img8.PNG" alt="img8" width="600" height="400" loading="lazy"></p>
<h3 id="heading-9-check-out-related-websites-using-related">9. Check out related websites using <code>related:</code></h3>
<p>If you want to know what all other websites are available on the internet that are similar to a particular website, then use the <code>related:</code> tag. </p>
<p>For example, a search on <strong>related:google.com</strong> will fetch all the websites that are similar to Google like Bing, Yahoo, DuckDuckGo, and so on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img9.PNG" alt="img9" width="600" height="400" loading="lazy"></p>
<h3 id="heading-10-use-cache-to-see-googles-cached-version-of-a-website">10. Use <code>cache:</code> to see Google's cached version of a website</h3>
<p>Google stores a cached version of websites to provide search results quickly. To see if Google has cached any site or not, just use the tag <code>cache:</code> in front of the website's URL. </p>
<p>This is especially helpful for <strong>web developers</strong> if they want to check if they are currently viewing a cached site or the latest version of a website after they have pushed some changes to the website. For example, a search for =&gt; <strong>cache:www.sohamderoy.dev</strong> on the day of writing this tutorial (that is, 4th Aug 2022) returns the following result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/img10a.png" alt="img10a" width="600" height="400" loading="lazy"></p>
<p>As you see, even though I am searching for the site on 4th August 2022, I still see a copy of the site from 3rd August 2022, as that is when Google has cached the website.</p>
<p>It is important to note that "Not all search operators return exhaustive results." as mentioned by <a target="_blank" href="https://support.google.com/websearch/answer/2466433?visit_id=637790664879774647-1036329470&amp;p=adv_pages_similar&amp;hl=en&amp;rd=1">Google</a> itself. </p>
<p>Still, I believe that these are some really handy tips that help you make an effective and efficient Google search. I hope I've explained them properly and have encouraged you to use them in your regular Google search.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Thanks for reading! I really hope you enjoyed reading this short article about how to google efficeiently and effectively and found this tutorial useful. </p>
<p>Do consider sharing it with your friends – I'd really appreciate that. Follow me on LinkedIn and Twitter and stay tuned for more amazing content! Peace out! 🖖</p>
<h3 id="heading-social-links">Social Links</h3>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/feed/">LinkedIn</a></li>
<li><a target="_blank" href="https://www.sohamderoy.dev/">Website</a></li>
<li><a target="_blank" href="https://blogs.sohamderoy.dev">Other Blogs by me</a></li>
<li><a target="_blank" href="https://twitter.com/_sohamderoy">Twitter</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Redux-Powered React App ]]>
                </title>
                <description>
                    <![CDATA[ The Problem We're Solving In many cases when we want to create a small application, we might have some components that declare and use their own state. And in a few cases, a component might want to share the state with its immediate children.  We can... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-redux-powered-react-app/</link>
                <guid isPermaLink="false">66ba5d40968a8cd3b478a8ea</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham De Roy ]]>
                </dc:creator>
                <pubDate>Wed, 03 Aug 2022 21:51:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Group-58.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-the-problem-were-solving">The Problem We're Solving</h2>
<p>In many cases when we want to create a small application, we might have some components that declare and use their own state. And in a few cases, a component might want to share the state with its immediate children. </p>
<p>We can handle these situations just by declaring states locally within a component – and maybe pass the state to its children in the form of props if needed (which is also known as prop drilling). </p>
<p>But if your application grows in size, you might need to pass state to a child which might be several steps down the hierarchy. You might also need to use a common state between sibling components. </p>
<p>Sure, in the case of state sharing between sibling components we can declare the state in their parents and then pass the state down to their children by prop drilling. But that may not always be feasible and has its own disadvantages that we will see in a bit. </p>
<p>Just consider the following diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Group-49.png" alt="Group-49" width="600" height="400" loading="lazy"></p>
<p>This is a schematic representation of a component file structure in a typical React application. </p>
<p>Let's say we need to share a common state between Child 5 and Child 6. In that case we can very well declare a state in their parent (that is, Child 2) and pass the state down to the two children (5 and 6). </p>
<p>All good as of now. But what if we need to have the same piece of state in Child 3? In that case we would need to declare the state in the common parent/grandparent of Children 5, 6, and 3 – that is, the App component. </p>
<p>Similarly what if we want to share a state between Children 4, 11, and 10 which are far away from each other in the tree? We would again need to create the state in the App component and then do multiple levels of prop drilling to pass the state from App to these components. </p>
<p>And as time passes and our app grows in size, it will start making our App component or any other such common parent component cluttered with unnecessary state declarations. These declarations aren't used directly by these components but are used by some of their far-down children.</p>
<h2 id="heading-disadvantages-of-multi-step-prop-drilling">Disadvantages of Multi-Step Prop Drilling</h2>
<p>There are primarily two disadvantages with multi level prop drilling. They are:</p>
<ul>
<li><strong>Unnecessary bloating of components:</strong> As discussed above, as our app grows in size, some common parent components might get bloated with unnecessary state declarations. And these components might not directly use those declarations, but they might be used by some of their distant children. Some other components might also get bloated which are just acting as prop passers to a child component. This will also negatively affect code readability.</li>
<li><strong>Unnecessary re-rendering:</strong> Unnecessary re-rendering is a big no no for a client-side application. Unnecessary re-renders can make an app slow, laggy, unresponsive and give a bad user experience. In React, re-renderings are caused by state or prop changes, among other reasons. So if a component is not actually using a state and is only acting as a passage from parent to child for the props, then it might also get re-rendered unnecessarily when the state/ props changes. See the below picture to understand it better</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Group-52-1.png" alt="Group-52-1" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-solution-to-this-problem">The Solution to this Problem</h2>
<p>This is why we use a state management app like Redux or MobX to handle the above scenarios of state management in a more uniform and efficient way. </p>
<p>In these kind of state management solutions like Redux, we can create a global state and put it in a store. Whichever component requires any state from that store can easily get it by subscribing to the store. This way we can get rid of both the above disadvantages.</p>
<ul>
<li><strong>Decluttering of components:</strong> Getting state on demand from the component which is "actually" using it can declutter many of our components to a large extent by removing all unnecessary prop drilling.</li>
<li><strong>No more unnecessary re-renders:</strong> As we do not have components that just act as a prop passer, we also avoid unnecessary re-rendering of those components. Only the components that uses a piece of the global state re-render when the state changes which is a desired behavior.</li>
</ul>
<h2 id="heading-what-youll-learn-here">What You'll Learn Here</h2>
<p>In this tutorial, you will learn how to set up your own Redux-powered React application. We will create a react application and setup up redux to be able to manage state globally so that any component can access any part of the state (hence the name redux powered react app). Some of the other alternative of redux that one can try are MobX, Zustand etc, but for this article we will be using redux.</p>
<p>We will go through how to create the store and connect it to the application. We'll also see how to write actions and dispatch them on user interactions. Then we'll see how to make reducers and update the store, read the store from other components which are children of App, and much more. </p>
<p>I'll also provide all the important code snippets along the way so that you can quickly spin up the application as you read and code along.</p>
<p>To give you a glimpse in the beginning, this is what we will build by the end:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/finalAppDemo.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We will be creating a basic application where we can add and remove items in a cart. We will manage the state changes in the Redux store and display the information in the UI.</p>
<h2 id="heading-before-we-start">Before We Start</h2>
<p>Before proceeding with this tutorial, you should be familiar with the Redux store, actions, and reducers.</p>
<p>If you're not, you can go through my last article that I wrote on Redux (if you haven't yet): <strong><a target="_blank" href="https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/">What is Redux? Store, Actions, and Reducers Explained for Beginners</a>.</strong> </p>
<p>This will help you understand the current article. In this previous tutorial, I tried to explain the fundamental principles/ concepts of Redux. I covered what the store is, what actions are, and how reducers work. I also discuss what makes Redux predictable along with an example.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/despicable-me-minions.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-initial-code-setup">Initial Code Setup</h2>
<p>Let's get everything we need setup for our project. Just follow these steps and you'll be up and running in no time.</p>
<h3 id="heading-1-create-a-react-app-with-the-create-react-app-command">1. Create a React app with the create-react-app command</h3>
<pre><code class="lang-node">npx create-react-app react-app-with-redux
</code></pre>
<h3 id="heading-2-go-to-the-newly-created-folder">2. Go to the newly created folder</h3>
<p>Just type this command to navigate to the new folder:</p>
<pre><code class="lang-shell">cd react-app-with-redux
</code></pre>
<h3 id="heading-3-install-redux-and-the-react-redux-libraries">3. Install Redux and the react-redux libraries</h3>
<p>You can install Redux and react-redux like this:</p>
<pre><code class="lang-node">npm install redux react-redux
</code></pre>
<h3 id="heading-4-run-the-application">4. Run the application</h3>
<p>You can run your new app with the following command:</p>
<pre><code class="lang-node">npm start
</code></pre>
<h2 id="heading-how-to-build-the-main-app">How to Build the Main App</h2>
<h3 id="heading-5-how-to-create-the-reducer">5. How to create the Reducer</h3>
<p>To create a reducer, first create a folder inside <code>src</code> named <code>actionTypes</code>. Then create a file inside it named <code>actionTypes.js</code>. This file will contain all the <strong>actions</strong> the application will be dealing with.</p>
<p>Add the following lines in <code>actionTypes.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ADD_ITEM = <span class="hljs-string">"ADD_ITEM"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> DELETE_ITEM = <span class="hljs-string">"DELETE_ITEM"</span>;
</code></pre>
<p>Since our app will have the functionality of adding and deleting items, we need the above two action types.</p>
<p>Next create a folder inside the <code>src</code> called <code>reducers</code> and create a new file in it named <code>cartReducer.js</code>. This file will contain all the reducer logic related to the <strong>cart</strong> component. </p>
<p><strong>Note</strong>: We will create the view/ UI in step 8, so hold on for that.</p>
<p>Add the following lines in <code>cartReducer.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { ADD_ITEM, DELETE_ITEM } <span class="hljs-keyword">from</span> <span class="hljs-string">"../actionTypes/actionTypes"</span>;

<span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">numOfItems</span>: <span class="hljs-number">0</span>,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">const</span> cartReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ADD_ITEM:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">numOfItems</span>: state.numOfItems + <span class="hljs-number">1</span>,
      };

    <span class="hljs-keyword">case</span> DELETE_ITEM:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">numOfItems</span>: state.numOfItems - <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>As we discussed it <a target="_blank" href="https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/">in my previous tutorial</a>, we created an <strong>initial state</strong> for the app and assigned it to the default parameter of <code>state</code> in the <code>cartReducer</code> function. </p>
<p>This function switches on the <strong>type of action</strong> dispatched. Then depending on whichever case matches with the action type, it makes necessary changes in the state and returns a fresh new instance of the updated state. </p>
<p>If none of the action types matche, then the state is returned as it is. </p>
<p>Finally we make a <strong>default export</strong> of the <code>cakeReducer</code> function to use it in the store creation process.</p>
<h3 id="heading-6-how-to-create-the-store-and-provide-it-to-the-app">6. How to create the store and provide it to the app</h3>
<p>Create a file inside <code>src</code> with the name <code>store.js</code> and create the store using this command:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> store = createStore()
</code></pre>
<p>Add the following lines in <code>store.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">"redux"</span>;
<span class="hljs-keyword">import</span> { cartReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">"./reducers/cartReducer"</span>;

<span class="hljs-keyword">const</span> store = createStore(cartReducer);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store;
</code></pre>
<p>Now it's time to provide this <code>store</code> to the <code>App</code> component. For this we'll use the <code>&lt;Provider&gt;</code> tag that we get from the <code>react-redux</code> library. </p>
<p>We wrap the whole <code>App</code> component inside the <code>&lt;Provider&gt;</code> tag using the following syntax:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// rest of the code ...</span>

&lt;Provider store={store}&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>App Component<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
        <span class="hljs-comment">// child components of App/ other logic</span>
&lt;/Provider&gt;

<span class="hljs-comment">// rest of the code ...</span>
</code></pre>
<p>By wrapping the <code>App</code> component inside the <code>&lt;Provider&gt;</code> tag, all the children component of <code>App</code> will get access of the <code>store</code>. You can read my previous article on <a target="_blank" href="https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/">What is Redux? Store, Actions, and Reducers Explained for Beginners</a> to know more.</p>
<p>Continuing with <code>App.js</code>, add the following lines to the file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">"./store"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>App Component<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h3 id="heading-7-create-the-actions">7. Create the Actions</h3>
<p>Now create a folder inside <code>src</code> called <code>actions</code> and create a file inside it called <code>cartAction.js</code>. Here we will add all the actions to be <strong>dispatched</strong> on some user interactions. </p>
<p>Add the following lines in the <code>cartAction.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { ADD_ITEM, DELETE_ITEM } <span class="hljs-keyword">from</span> <span class="hljs-string">"../actionTypes/actionTypes"</span>;

<span class="hljs-keyword">const</span> addItem = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">type</span>: ADD_ITEM,
  };
};

<span class="hljs-keyword">const</span> deleteItem = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">type</span>: DELETE_ITEM,
  };
};

<span class="hljs-keyword">export</span> { addItem, deleteItem };
</code></pre>
<p>In the above code we created two action creators (pure JS functions that returns <code>action</code> object) called <code>addItem()</code> and <code>deleteItem()</code>. Both the action creators return <code>action</code> objects with a specific <code>type</code>. </p>
<p><strong>Note</strong>: Each <code>action</code> object must have a unique <code>type</code> value. Along with it, any additional data passed with the action object is optional and will depend on the logic used for updating the <code>state</code></p>
<h3 id="heading-8-how-to-create-the-viewui">8. How to create the view/UI</h3>
<p>Now that we have created all the required entities such as the store, actions, and Reducers, it's time to create the UI elements. </p>
<p>Create a <code>component</code> folder inside <code>src</code> and a <code>Cart.js</code> file inside it. Add the following lines inside <code>Cart.js</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Cart = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Number of items in Cart:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"green"</span>&gt;</span>Add Item to Cart<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"red"</span>&gt;</span>Remove Item from Cart<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Cart;
</code></pre>
<p>Add this <code>Cart</code> component in the <code>App.js</code> file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">"./store"</span>;
<span class="hljs-keyword">import</span> Cart <span class="hljs-keyword">from</span> <span class="hljs-string">"./component/Cart"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Cart</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Just to make it a bit presentable, I have added a bit of basic styling in <code>App.css</code> as follows:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">button</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">letter-spacing</span>: <span class="hljs-number">2px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">400</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">23px</span> <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">text-decoration</span>: none;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">0px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
}
<span class="hljs-selector-class">.green</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">6</span>, <span class="hljs-number">172</span>, <span class="hljs-number">0</span>);
}
<span class="hljs-selector-class">.red</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">221</span>, <span class="hljs-number">52</span>, <span class="hljs-number">66</span>);
}
<span class="hljs-selector-class">.red</span><span class="hljs-selector-pseudo">:disabled</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">193</span>, <span class="hljs-number">191</span>, <span class="hljs-number">191</span>);
  <span class="hljs-attribute">cursor</span>: not-allowed;
}
<span class="hljs-selector-class">.cart</span> {
  <span class="hljs-attribute">text-align</span>: center;
}
</code></pre>
<p>This is how the UI looks as of now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot-2022-05-20-at-20.01.01.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-9-how-to-read-and-access-the-store-using-the-useselector-hook">9. How to read and access the store using the <code>useSelector</code> hook</h3>
<p><code>useSelector</code> is a hook provided by the <strong>react-redux</strong> library that helps us read the <code>store</code> and its content(s). </p>
<p>Import the hook from <code>react-redux</code> and use the following syntax to read the store with <code>useSelector</code> hook:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useSelector } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-comment">// rest of the code</span>
<span class="hljs-keyword">const</span> state = useSelector(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state);

<span class="hljs-comment">// rest of the code</span>
</code></pre>
<p>After adding the <code>useSelector</code> hook, your <code>Cart.js</code> file will look something like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useSelector } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;

<span class="hljs-keyword">const</span> Cart = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> state = useSelector(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"store"</span>, state);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Number of items in Cart:<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"green"</span>&gt;</span>Add Item to Cart<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"red"</span>&gt;</span>Remove Item from Cart<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Cart;
</code></pre>
<p>Console logging the state will give us the initial state that we set in the reducer file in step 5.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot-2022-05-21-at-01.10.28.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-10-how-to-dispatch-an-action-on-button-click-with-the-usedispatch-hook">10. How to dispatch an action on button click with the <code>useDispatch</code> hook</h3>
<p>The react-redux library gives us another hook called the <code>useDispatch</code> hook. It helps us dispatch the actions or action creators which in turn return actions. The syntax is as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> dispatch = useDispatch();

dispatch(actionObject or calling the action creator);
</code></pre>
<p>Thus adding a dispatcher into our <code>Cart.js</code> will finally make the file look something like this:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useSelector, useDispatch } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> { addItem, deleteItem } <span class="hljs-keyword">from</span> <span class="hljs-string">"../actions/cartAction"</span>;

<span class="hljs-keyword">const</span> Cart = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> state = useSelector(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state);
  <span class="hljs-keyword">const</span> dispatch = useDispatch();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Number of items in Cart: {state.numOfItems}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
        <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> {
          dispatch(addItem());
        }}
      &gt;
        Add Item to Cart
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
        <span class="hljs-attr">disabled</span>=<span class="hljs-string">{state.numOfItems</span> &gt;</span> 0 ? false : true}
        onClick={() =&gt; {
          dispatch(deleteItem());
        }}
      &gt;
        Remove Item to Cart
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Cart;
</code></pre>
<p>Note how on click of the <strong>Add Item to Cart</strong> button, we <code>dispatch</code> the action creator <code>addItem()</code> that we created in step no. 7. </p>
<p>Similarly on click on the <strong>Remove Item from Cart</strong> button, we dispatch the action creator with <code>deleteItem()</code>. </p>
<p>The <code>state</code> variable stores the state of the app, which is basically an object with a key <code>numOfItems</code>. So <code>state.numOfItems</code> gives us the current number of items value in the store. </p>
<p>We display this information in the view in the line <code>&lt;h2&gt;Number of items in Cart: {state.numOfItems}&lt;/h2&gt;</code>. </p>
<p>To dig a bit deeper, when a user clicks the Add Item to Cart button, it dispatches the <code>addItem()</code> action creator. This, in turn, returns an <code>action</code> object with type <code>type: ADD_ITEM</code>. </p>
<p>As mentioned in <a target="_blank" href="https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/">my previous tutorial</a>, when an action is dispatched, all the reducers become active. </p>
<p>Currently in this example we have only one reducer – <code>cartReducer</code>. So it becomes active and listens to the <code>action</code> dispatched. </p>
<p>As shown in step 5, the reducer takes the state and the action as input, switches on the <code>action type</code> and <strong>returns the fresh new instance of the updated state</strong>. </p>
<p>In this example, when the action with <code>type: ADD_ITEM</code> matches the first switch case, it first makes a copy of the entire state using the spread operator <code>...state</code>. Then it makes the necessary update – which in the case of adding items is <code>numOfItems: state.numOfItems + 1</code> (that is increasing the <code>numOfItems</code> by 1). </p>
<p>Similarly, using the same logic, on clicking on the Remove Item from Cart button, an action with type <code>type: DELETE_ITEM</code> is dispatched which goes and decreases the <code>numOfItems</code> by 1. </p>
<p>Here is the demo of the working app:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/finalAppDemo-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice how we were able to control the behavior of the Remove Item from Cart button based on the value of <code>numOfItems</code> in the Redux store. As a negative number of items does not makes sense, we disabled the Remove Item from Cart button if <code>state.numOfItems &lt;= 0</code>. </p>
<p>This way we are able to prevent the user from decreasing the number of items in the cart if its already 0. </p>
<p>This was a basic example to show you how we can <strong>control the behavior of various DOM elements</strong> based on the internal state of the app. </p>
<p>And there you go! We just finished setting up our first Redux-powered React application. Now you can go ahead and create various other components based on your requirements and share a common global state among them.</p>
<h2 id="heading-github-repo">GitHub Repo</h2>
<p>Here's the GitHub repo of the project so you can examine the full source code if you like: <a target="_blank" href="https://github.com/sohamderoy/blog-setup-react-app-with-redux/tree/master">GitHub repo</a></p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we learned how to quickly spin up a Redux-powered React application. </p>
<p>Along the way, we learned how to:</p>
<ul>
<li>Create actions, action creators, reducers, and the store</li>
<li>Provide the store to the app using <code>&lt;Provider&gt;</code></li>
<li>Read/ access the store from components using the <code>useSelector</code> hook and display the state information in the UI</li>
<li>Dispatch the actions on user events such as button clicks, using the <code>useDispatch</code> hook</li>
<li>Control the DOM elements' behavior with logic based on the state of the application</li>
<li>We learnt what are the disadvantages of in-efficient state management and multiple level of prop drilling </li>
</ul>
<h2 id="heading-additional-resources">Additional Resources</h2>
<p>Here are some additional resources that you can look into to learn more about Redux</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/">What is Redux? Store, Actions, and Reducers Explained for Beginners</a></li>
<li><a target="_blank" href="https://redux.js.org/introduction/getting-started">Official Redux Docs</a></li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Thanks for reading! I really hope you enjoyed reading about how to spin up a Redux-powered React application and found this tutorial useful.</p>
<p>Do consider sharing it with your friends, as I'd really appreciate that. Follow me on LinkedIn and Twitter and stay tuned for more amazing content! Peace out! 🖖</p>
<h3 id="heading-social-links">Social Links</h3>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/feed/">LinkedIn</a></li>
<li><a target="_blank" href="https://www.sohamderoy.dev/">Website</a></li>
<li><a target="_blank" href="https://blogs.sohamderoy.dev">Other Blogs by me</a></li>
<li><a target="_blank" href="https://twitter.com/_sohamderoy">Twitter</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Redux? Store, Actions, and Reducers Explained for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Redux is a predictable state container for JavaScript apps. So what does that really mean? If we dig deeper into this statement, we see that Redux is a state management library that you can use with any JS library or framework like React, Angular, or... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/</link>
                <guid isPermaLink="false">66ba5d480013ba5d5012bcb5</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham De Roy ]]>
                </dc:creator>
                <pubDate>Wed, 27 Jul 2022 15:48:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Group-60.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Redux is a predictable state container for JavaScript apps. So what does that really mean?</p>
<p>If we dig deeper into this statement, we see that Redux is a state management library that you can use with any JS library or framework like React, Angular, or Vue.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/1-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this article, we'll be covering the fundamentals of Redux. We will learn what Redux is at its core along with its three key principles. </p>
<p>We will also see how some of its core building blocks work, such as store, actions, and reducers and how they all come together and make Redux the global state management library that it is.</p>
<p>As a prerequisite, I will be assuming that you're familiar with React.</p>
<h2 id="heading-why-use-redux">Why Use Redux?</h2>
<p>Well, an application has its state, which can be a combination of the states of its internal components. </p>
<p>Let's take an e-commerce website for example. An e-commerce website will have several components like the cart component, user profile component, previously viewed section component, and so on. </p>
<p>We'll take the cart component which displays the number of items in a user's cart. The state of the cart component will consist of all the items the user has added to the cart and the total number of those items. At all times the application is up and running, this component has to show the updated number of items in the user's cart. </p>
<p>Whenever a user adds an item to the cart, the application has to internally handle that action by adding that item to the cart object. It has to maintain its state internally and also show the user the total number of items in the cart in the UI. </p>
<p>Similarly, removing an item from the cart should decrease the number of items in the cart internally. It should remove the item from the cart object and also display the updated total number of items in the cart in the UI. </p>
<p>We may very well maintain the internal state of the components inside them, but as and when an application grows bigger, it may have to share some state between components. This is not just only to show them in the view, but also to manage or update them or perform some logic based on their value. </p>
<p>This task of handling multiple states from multiple components efficiently can become challenging when the application grows in size.</p>
<p>This is where Redux comes into the picture. Being a state management library, Redux will basically store and manage all the application's states. </p>
<p>It also provides us with some important APIs using which we can make changes to the existing state as well as fetch the current state of the application. </p>
<h2 id="heading-what-makes-redux-predictable">What Makes Redux Predictable?</h2>
<p>State is <strong>Read-only</strong> in Redux. What makes Redux predictable is that to make a change in the state of the application, we need to dispatch an action which describes what changes we want to make in the state. </p>
<p>These actions are then consumed by something known as reducers, whose sole job is to accept two things (the action and the current state of the application) and return a new updated instance of the state. </p>
<p>We'll talk more about actions and reducers in the following sections. </p>
<p>Note that reducers do not change any part of the state. Rather a reducer produces a new instance of the state with all the necessary updates. </p>
<p>According to <a class="user-mention" href="https://hashnode.com/@gaearon">Dan Abramov</a> (the creator of Redux) himself,  </p>
<blockquote>
<p>"Actions can be recorded and replayed later, so this makes state management predictable. With the same actions in the same order, you're going to end up in the same state." </p>
</blockquote>
<p>So continuing with our above example of an e-commerce website, if the initial state of the cart is that it has 0 items, then an action of <strong>adding one item</strong> to the cart will increase the number of items in the cart by 1. And firing the action of <strong>adding one item</strong> to the cart again will increase the number of items in the cart to 2. </p>
<p>Given an initial state, with a specific list of <strong>actions</strong> in a specific order, it'll always provide us with the exact same final state of the entity. This is how Redux makes state management predictable.</p>
<p>In the following section, we will dive deep into the core concepts of Redux – the store, actions and reducers.</p>
<h2 id="heading-core-principles-of-redux">Core Principles of Redux</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-1-what-is-the-redux-store">1. What is the Redux Store?</h3>
<blockquote>
<p>The global state of an application is stored in an object tree within a single store – <a target="_blank" href="https://redux.js.org/understanding/thinking-in-redux/three-principles">Redux docs</a></p>
</blockquote>
<p>The Redux store is the main, central bucket which stores all the states of an application. It should be considered and maintained as a <strong>single source of truth</strong> for the state of the application. </p>
<p>If the <code>store</code> is provided to the <strong>App.js</strong> (by wrapping the <code>App</code> component within the <code>&lt;Provider&gt;</code> <code>&lt;/Provider&gt;</code> tag) as shown in the code snippet below, then all its children (children components of <code>App.js</code>) can also access the state of the application from the store. This makes it act as a global state. </p>
<pre><code class="lang-js"><span class="hljs-comment">// src/index.js</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>

<span class="hljs-keyword">import</span> { App } <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>
<span class="hljs-keyword">import</span> createStore <span class="hljs-keyword">from</span> <span class="hljs-string">'./createReduxStore'</span>

<span class="hljs-keyword">const</span> store = createStore()

<span class="hljs-comment">// As of React 18</span>
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>))
root.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The state of the whole application is stored in the form of a <strong>JS object tree</strong> in a <strong>single store</strong> as shown below. </p>
<pre><code class="lang-js"><span class="hljs-comment">// this is how the store object structure looks like</span>
{
    <span class="hljs-attr">noOfItemInCart</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">cart</span>: [
        {
            <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Chamber of Secrets"</span>,
            <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>,
        },
        {
            <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Prisoner of Azkaban"</span>,
            <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>
        }
    ]
}
</code></pre>
<h3 id="heading-2-what-are-actions-in-redux">2. What Are Actions in Redux?</h3>
<blockquote>
<p>The only way to change the state is to emit an action, which is an object describing what happened – <a target="_blank" href="https://redux.js.org/understanding/thinking-in-redux/three-principles">Redux Docs</a></p>
</blockquote>
<p>As mentioned above, state in Redux is read-only. This helps you restrict any part of the view or any network calls to write/update the state directly. </p>
<p>Instead, if anyone wants to change the state of the application, then they'll need to express their intention of doing so by <strong>emitting or dispatching an action</strong>. </p>
<p>Let's take the example of the above store example where we have 2 books in the store: <em>"Harry Potter and the Chamber of Secrets"</em> and <em>"Harry Potter and the Prisoner of Azkaban"</em>. There's just one copy of each. </p>
<p>Now if the user wants to add another item to the cart, then they will have to click on the <strong>"Add to Cart"</strong> button next to the item. </p>
<p>On the click of the <strong>"Add to Cart"</strong> button, an action will be dispatched. This action is nothing but a JS object describing what changes need to be done in the store. Something like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Rest of the code</span>

<span class="hljs-keyword">const</span> dispatch = useDispatch()

<span class="hljs-keyword">const</span> addItemToCart = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-keyword">return</span> {
    <span class="hljs-attr">type</span>: <span class="hljs-string">"ADD_ITEM_TO_CART"</span>
    <span class="hljs-attr">payload</span>: {
        <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Goblet of Fire"</span>,
        <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>,
        }
    }
}

&lt;button onClick = {<span class="hljs-function">() =&gt;</span> dispatch(addItemToCart())}&gt;Add to cart&lt;/button&gt;

<span class="hljs-comment">// Rest of the code</span>
</code></pre>
<p>Note how in the above example, we dispatch an action on click of the button. Or rather, to be more specific, we dispatch something known as an <strong>action creator</strong> – that is, the function <code>addItemToCart()</code>. This in turn returns an <code>action</code> which is a plain JS object describing the purpose of the action denoted by the <code>type</code> key along with any other data required for the state change. In this case, it's the name of the book to be added to the cart denoted by the <code>payload</code> key. </p>
<p><strong>Every action must have at least</strong> a <code>type</code> associated with it. Any other detail that needs to be passed is optional and will depend on the type of action we dispatch. </p>
<p>For example, the above code snippet dispatches the following action:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Action that got created by the action creator addItemToCart()</span>

{
    <span class="hljs-attr">type</span>: <span class="hljs-string">"ADD_ITEM_TO_CART"</span> <span class="hljs-comment">// Note: Every action must have a type key</span>
    <span class="hljs-attr">payload</span>: {
        <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Goblet of Fire"</span>,
        <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>,
    }
}
</code></pre>
<h3 id="heading-3-what-are-reducers-in-redux">3. What Are Reducers in Redux?</h3>
<blockquote>
<p>To specify how the state tree is transformed by actions, we write pure reducers – <a target="_blank" href="https://redux.js.org/understanding/thinking-in-redux/three-principles">Redux docs</a></p>
</blockquote>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Reducers, as the name suggests, take in two things: <strong>previous state</strong> and <strong>an action</strong>. Then they reduce it (read it return) to one entity: the <strong>new updated instance of state</strong>. </p>
<p>So reducers are basically pure JS functions which take in the previous state and an action and return the newly updated state. </p>
<p>There can either be one reducer if it is a simple app or multiple reducers taking care of different parts or slices of the global state in a bigger application. </p>
<p>For example, there can be a reducer handling the state of the cart in a shopping application, then there can be a reducer handling the user details part of the application, and so on. </p>
<p>Whenever an action is dispatched, <strong>all the reducers are activated</strong>. Each reducer filters out the action using a switch statement switching on the <strong>action type</strong>. Whenever the switch statement matches with the action passed, the corresponding reducers take the necessary action to make the update and return a fresh new instance of the global state. </p>
<p>Continuing with our above example, we can have a reducer as follows:</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> initialCartState = {    
    <span class="hljs-attr">noOfItemInCart</span>: <span class="hljs-number">0</span>,          
    <span class="hljs-attr">cart</span>: []                              
}

<span class="hljs-comment">// <span class="hljs-doctag">NOTE:</span> </span>
<span class="hljs-comment">// It is important to pass an initial state as default to </span>
<span class="hljs-comment">// the state parameter to handle the case of calling </span>
<span class="hljs-comment">// the reducers for the first time when the </span>
<span class="hljs-comment">// state might be undefined</span>

<span class="hljs-keyword">const</span> cartReducer = <span class="hljs-function">(<span class="hljs-params">state = initialCartState, action</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span> (action.type) {
        <span class="hljs-keyword">case</span> <span class="hljs-string">"ADD_ITEM_TO_CART"</span>: 
            <span class="hljs-keyword">return</span> {
                ...state,
                <span class="hljs-attr">noOfItemInCart</span>: state.noOfItemInCart + <span class="hljs-number">1</span>,
                <span class="hljs-attr">cart</span> : [
                    ...state.cart,
                    action.payload
                ]
            }
        <span class="hljs-keyword">case</span> <span class="hljs-string">"DELETE_ITEM_FROM_CART"</span>:
            <span class="hljs-keyword">return</span> {
                <span class="hljs-comment">// Remaining logic</span>
            }
        <span class="hljs-attr">default</span>: 
            <span class="hljs-keyword">return</span> state  
    }       <span class="hljs-comment">// Important to handle the default behaviour</span>
}           <span class="hljs-comment">// either by returning the whole state as it is </span>
            <span class="hljs-comment">// or by performing any required logic</span>
</code></pre>
<p>In the above code snippet, we created a reducer called <code>cartReducer</code> which is a pure JS function. This function accepts two parameters: <code>state</code> and <code>action</code>. </p>
<p>Note that the <code>state</code> parameter is a default parameter which accepts an initial state. This is to handle the scenario when <strong>the reducer is called for the first time</strong> when the <code>state</code> value is <code>undefined</code>.  </p>
<p>Also note that every reducer should handle the <code>default</code> case where, if none of the switch cases match with the passed action, then the reducer should return <code>state</code> as it is or perform any required logic on it before passing the state.</p>
<p>Whenever we dispatch an action with a certain type, we need to make sure to have appropriate reducers to handle that action. </p>
<p>In the above example, on clicking the button, we had dispatched an <strong>action</strong> with an <strong>action creator</strong> called <code>addItemToCart()</code>. This action creator has dispatched an action with the <code>type</code> <code>ADD_ITEM_TO_CART</code>. </p>
<p>Next, we have created a <strong>reducer</strong> called <code>cartReducer</code> which takes the state (with the default initial state) and the action as parameters. It switches on the <strong>action type</strong>, and then whichever case matches with the dispatched action type, it makes the necessary update and returns the fresh new version of the updated state. </p>
<p>Note here that <strong>state in redux is immutable</strong>. So, the reducers make a copy of the entire current state first, make the necessary changes, and then return a fresh new instance of the state – with all the necessary changes/ updates. </p>
<p>So in the above example, we first make a copy of the entire state using the spread operator <code>...state</code>. Then we increment the <code>noOfItemInCart</code> by 1, update the cart array by adding the new object passed in the <code>action.payload</code> shown below, and then finally return the updated object.</p>
<pre><code class="lang-js">{
    <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Goblet of Fire"</span>,
    <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>,
}
</code></pre>
<p>After the reducers have updated the state, if we go and <code>console.log</code> the <code>state</code>, then we would see the following result:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Updated store</span>

{
    <span class="hljs-attr">noOfItemInCart</span>: <span class="hljs-number">3</span>, <span class="hljs-comment">// Incremented by 1</span>
    <span class="hljs-attr">cart</span>: [
        {
            <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Chamber of Secrets"</span>,
            <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>,
        },
        {
            <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Prisoner of Azkaban"</span>,
            <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>
        },
        { <span class="hljs-comment">// Newly added object</span>
            <span class="hljs-attr">bookName</span>: <span class="hljs-string">"Harry Potter and the Goblet of Fire"</span>,
            <span class="hljs-attr">noOfItem</span>: <span class="hljs-number">1</span>,
        }
    ]
}
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>In short, the following three principles completely govern how Redux works:</p>
<ul>
<li>The global state of an application is stored in an object tree within a single <strong>store</strong></li>
<li>The only way to change the state is to emit an <strong>action</strong>, which is an object describing what happened</li>
<li>To specify how the state tree is transformed by actions, we write <strong>pure reducers</strong></li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Thanks for reading! I really hope you enjoyed learning about Redux and its core principles and found this tutorial useful. </p>
<p>Do consider sharing it with your friends, I'd really appreciate that.  Stay tuned for more amazing content. Peace out! 🖖</p>
<h3 id="heading-social-links">Social Links</h3>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/feed/">LinkedIn</a></li>
<li><a target="_blank" href="https://www.sohamderoy.dev/">Website</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/author/sohamderoy">Other Blogs</a></li>
<li><a target="_blank" href="https://twitter.com/_sohamderoy">Twitter</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Center a Div with CSS – 10 Different Ways ]]>
                </title>
                <description>
                    <![CDATA[ As a web developer, sometimes centering a div feels like one of the toughest jobs on planet Earth.  Well, not anymore. In this article, you'll learn 10 different ways to center a div. We will explore how to center divs using the CSS position property... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-center-a-div-with-css-10-different-ways/</link>
                <guid isPermaLink="false">66ba5d43e530197d3818e1a2</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham De Roy ]]>
                </dc:creator>
                <pubDate>Wed, 20 Jul 2022 22:08:19 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Group-49.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a web developer, sometimes <strong>centering a div</strong> feels like one of the toughest jobs on planet Earth. </p>
<p>Well, not anymore. In this article, you'll learn 10 different ways to center a <code>div</code>. We will explore how to center divs using the CSS <strong>position</strong> property, CSS <strong>Flexbox</strong>, and CSS <strong>Grid</strong>. </p>
<p>After reading this whole article, I am confident that you will start centering <code>divs</code> like a pro.</p>
<h2 id="heading-how-to-center-a-div">How to Center a <code>Div</code></h2>
<p>For this tutorial, I will be using the same HTML for all 10 methods that we'll discuss below. The HTML just contains a parent <code>div</code> and a child <code>div</code> inside it. </p>
<p>The main aim of this article is to center the inner <code>div</code> with respect to its parent. I will only be changing the CSS files, but you'll be able to see all 10 different methods take effect.</p>
<p>The main HTML file goes like this:</p>
<pre><code class="lang-HTML"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Centering divs<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./basicStyle.css"</span> /&gt;</span>
    <span class="hljs-comment">&lt;!-- Change the link of CSS file here --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">""</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
      * {
        <span class="hljs-attribute">box-sizing</span>: border-box;
        <span class="hljs-attribute">margin</span>: <span class="hljs-number">0px</span>;
        <span class="hljs-attribute">padding</span>: <span class="hljs-number">0px</span>;
      }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"parentContainer"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"childContainer"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>With just the basic styling as given in the following lines:</p>
<pre><code class="lang-CSS"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f55353</span>;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#feb139</span>;
}
</code></pre>
<p>We will get something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot-2022-05-27-at-15.02.59.png" alt="Image" width="600" height="400" loading="lazy">
<em>What the basic HTML and CSS styling gives us.</em></p>
<p>We just make a parent <code>div</code> and give it a <code>width</code> and <code>height</code> of <code>400px</code>, and a <code>color</code> of <code>#f55353</code>. </p>
<p>Similarly we create a child <code>div</code> inside it and give it a <code>width</code> and <code>height</code> of <code>100px</code> and give it a <code>color</code> of <code>#feb139</code>.</p>
<p>The final goal of this article will be to make this transformation:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Group-23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-center-a-div-using-the-css-position-property">How to Center a Div using the CSS <code>position</code> Property</h2>
<h3 id="heading-1-how-to-use-position-relative-absolute-and-top-left-offset-values">1. How to use position: relative, absolute and top, left offset values</h3>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">position</span>: relative;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(-<span class="hljs-number">50%</span>, -<span class="hljs-number">50%</span>);
}
</code></pre>
<p>The <strong>position</strong> property in CSS sets how the element is positioned on the page. The default value of the position property is <code>static</code>. The other values that the position property takes are <code>relative</code>, <code>absolute</code>, <code>fixed</code> and <code>sticky</code>. </p>
<p>Now when we give a <code>position: absolute</code> to a DOM element, it <strong>becomes absolute with respect to the whole page</strong>. This would be useful if we wanted to center the <code>div</code> with respect to the whole page. </p>
<p>On the other hand, setting the parent element to <code>position: relative</code>, makes the children element (with <code>position: absolute</code>) <strong>absolute, relative to the parent element and not the whole page</strong>. </p>
<p>In the above example we do just that. We give the parent element a <code>position: relative</code> and child a <code>position: absolute</code>. </p>
<p>Along with the position property, we can specify four other properties viz. <code>top</code>, <code>right</code>, <code>bottom</code> and <code>left</code> which then determines the final location/ position of the element. </p>
<p>The <code>top</code> and <code>bottom</code> specify the <strong>vertical positioning</strong> of the element where as <code>left</code> and <code>right</code> specify the <strong>horizontal positioning</strong>. </p>
<h3 id="heading-2-how-to-use-position-relative-and-absolute-top-left-right-and-bottom-offset-values-and-margin-auto">2. How to use position: relative and absolute, top, left, right and bottom offset values and margin: auto</h3>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">position</span>: relative;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">bottom</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">right</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">margin</span>: auto;
}
</code></pre>
<p>Continuing with our knowledge of positions from point 1 above, we use the <code>margin</code> property in CSS here. <code>margin: auto</code> lets the browser select a <strong>suitable margin</strong> for the child element. </p>
<p>In most of the cases it allows the child element to take its specified width and the browser <strong>distributes the remaining space equally</strong> between the left and right margin pair or top and bottom margin pair or amongst both pairs. </p>
<p>If we mention only <code>top: 0</code>, <code>bottom: 0</code> and <code>margin: auto</code>, it centers the child element <strong>vertically</strong>. </p>
<p>Similarly if we mention only <code>left: 0</code>, <code>right: 0</code> and <code>margin: auto</code>, then it will center the child <strong>horizontally</strong>. </p>
<p>And if we mention all the properties as shown in the code block above, then we get a perfectly <strong>centered div both horizontally and vertically</strong>.</p>
<h2 id="heading-how-to-center-a-div-using-css-flexbox">How to Center a Div Using CSS Flexbox</h2>
<h3 id="heading-3-how-to-use-flexbox-justify-content-and-align-item">3. How to use Flexbox, justify-content, and align-item</h3>
<p>The above two methods are based on more of a classical method of aligning elements in the page. The modern approaches makes use of <strong>Flexbox</strong> (for one directional layout modeling) and <strong>Grid</strong> layout (for more complex two dimensional layout modeling) properties. </p>
<p>Let's see the Flexbox approach:</p>
<p>Flexbox is not just a single property, but it is a module which comprises of a set of properties. Some of these properties are meant to be for the <strong>container</strong> (that is, the parent container) and some for the <strong>child elements</strong> inside it.</p>
<p>The below diagram shows a list of properties that are meant for parent and child elements with respect to Flexbox.
<img src="https://www.freecodecamp.org/news/content/images/2022/07/Group-42.png" alt="Group-42" width="600" height="400" loading="lazy"></p>
<p>Now it is not possible to cover all the properties in this article. Rather let's look into some of the properties we are using in this article.</p>
<p>As mentioned above, there are two different entities in the Flexbox model, the parent container and the children element. </p>
<p>The <code>display: flex</code> property defines a container as a flex container. <code>flex-direction</code> is another parent container property which can take in either of the four values <code>row</code> (default value), <code>row-reverse</code>, <code>column</code> and <code>column-reverse</code>. </p>
<p>When working with Flexbox, we need to take two different axes into consideration, that is the <strong>main axis</strong> and <strong>cross axis</strong>. </p>
<p>For the cases where <code>flex-direction</code> is <code>row</code> or <code>row-reverse</code>, the <strong>horizontal axis is the main axis and vertical axis is the cross axis</strong>. </p>
<p>Similarly, when the <code>flex-direction</code> is <code>column</code> or <code>column-reverse</code>, then the <strong>vertical axis is the main axis and horizontal axis is the cross axis.</strong> Refer to the below diagrams for visual clarity:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Group-43.png" alt="Group-43" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Group-44.png" alt="Group-44" width="600" height="400" loading="lazy"></p>
<p>The <code>justify-content</code> property of the parent container defines the alignment of its children along the main axis. Thus <code>justify-content: center</code> sets the alignment of all its child elements at the center with respect to the main axis.</p>
<p>Similarly, the <code>align-items</code> property of the parent container defines the alignment of its children along the cross axis. Thus <code>align-items: center</code> sets the alignment of all its child elements at the center with respect to the cross axis.</p>
<p>So the below code block will perfectly align our child element at the center of the parent element both vertically and horizontally. </p>
<p>In this method, we do not need to specify anything explicitly for the child element. <code>display: flex</code>, <code>justify-content</code> and <code>align-items</code> handle everything from the parent component.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
}
</code></pre>
<h3 id="heading-4-how-to-use-flexbox-justify-content-and-align-self">4. How to Use Flexbox, justify-content, and align-self</h3>
<p>This method is just an alternative to the above method and is quite similar to it.</p>
<p>But in place of using the <code>align-items</code> property (in the parent container property), which sets the alignment for <strong>all the childern</strong> elements with respect to cross axis, we use <code>align-self</code> (in the child elements) which sets the alignment of <strong>individual flex items</strong> on the cross axis.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">align-self</span>: center;
}
</code></pre>
<h3 id="heading-5-how-to-use-flexbox-and-margin-auto">5. How to Use Flexbox and margin: auto</h3>
<p>Flexbox gives us very powerful alignment and space distribution capabilities. Also as mentioned above, <code>margin: auto</code> lets the browser select a suitable margin for the child element. </p>
<p>In most cases it allows the child element to take its specified width and the browser distributes the remaining space equally between the left and right margin pair or top and bottom margin pair or amongst both the pairs. </p>
<p>This means that setting the parent container as <code>flex</code> and giving the child a <code>margin: auto</code> alows the browser to evenly distribute the leftover space along both the vertical and horizontal directions.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: flex;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">margin</span>: auto;
}
</code></pre>
<h2 id="heading-how-to-center-a-div-using-css-grid">How to Center a Div Using CSS Grid</h2>
<h3 id="heading-6-how-to-use-grid-justify-content-and-align-items">6. How to Use Grid, justify-content, and align-items</h3>
<p>CSS Grid or just Grid is used for <strong>two dimensional</strong> layout modeling compared to Flexbox which you use for <strong>one dimensional</strong> modeling. </p>
<p>Similar to Flexbox, we have the concept of a grid container or parent container and grid items or children items. </p>
<p>The below diagram lists down all the properties you can use for the parent and children. As CSS Grid is a huge topic in itself, it's not in the scope of this article to discuss about each and every property. So let's discuss the properties that we're using in this article.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/Group-45.png" alt="Group-45" width="600" height="400" loading="lazy"></p>
<p><code>display: grid</code> initiates an element to become a grid container.</p>
<p><code>justify-items</code> and <code>align-items</code> align the items inside the grid along the inline (row) axis and block (column) axis respectively.</p>
<p>On the other hand, if the total size of the grid is less than the grid container (which can happen if all the grid items are sized with non-flexible units like px), then in that case we can control the alignment of the grid within the grid container using <code>justify-content</code> and <code>align-content</code>.</p>
<p><code>justify-content</code> and <code>align-content</code> aligns the grid along the inline (row) axis and block (column) axis respectively.</p>
<p>You can find a comprehensive explanation of all these properties here: <a target="_blank" href="https://css-tricks.com/snippets/css/complete-guide-grid/">A Complete Guide to Grid</a></p>
<p>As for our case there is only one <strong>grid cell</strong> and only one child element inside it, so we can use <code>justify-content</code> or <code>justify-items</code> as well as <code>align-content</code> or <code>align-items</code> interchangeably and get the same result.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
}
</code></pre>
<h3 id="heading-7-how-to-use-grid-and-place-items">7. How to Use Grid and place-items</h3>
<p>You can use <code>place-items</code> to set both <code>align-items</code> and <code>justify-items</code> properties in the same declaration. Similarly <code>place-content</code> sets both <code>justify-content</code> and <code>align-content</code> is the same declaration.</p>
<p>As mentioned above, in this use case we can use <code>justify-content</code> or <code>justify-items</code> as well as <code>align-content</code> or <code>align-items</code> interchangeably. In the same way we can also use <code>place-items</code> as well as <code>place-content</code> interchangeably and get the same result (specifically for this use case. For any other use case we need to analyse which property should be used).</p>
<pre><code class="lang-CSS"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">place-items</span>: center;
}
</code></pre>
<h3 id="heading-8-how-to-use-grid-align-self-and-justify-self">8. How to Use Grid, align-self, and justify-self</h3>
<p>Similar to Flexbox, Grid also supports individual grid item alignment using the <code>align-self</code> and <code>justify-self</code> properties (properties to be specified in the children element). </p>
<p><code>justify-self</code> aligns grid items inside a grid cell along the inline (row) axis whereas <code>align-self</code> aligns the grid items inside the grid cell along the block (column) axis.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: grid;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">align-self</span>: center;
  <span class="hljs-attribute">justify-self</span>: center;
}
</code></pre>
<h3 id="heading-9-how-to-use-grid-and-place-self">9. How to Use Grid and place-self</h3>
<p>The <code>place-self</code> property sets both <code>justify-self</code> and <code>align-self</code> properties in a single declaration. So assigning a child element to <code>place-self: center</code> centers the child both vertically and horizontally.</p>
<pre><code class="lang-CSS"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: grid;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">place-self</span>: center;
}
</code></pre>
<h3 id="heading-10-how-to-use-grid-and-margin-auto">10. How to Use Grid and margin: auto</h3>
<p>Similar to Flexbox, Grid also gives us powerful alignment and space distribution capabilities. </p>
<p>As seen in point 5, we can do a similar process with Grid instead of using Flexbox and we'll get the same result if we asign <code>margin: auto</code> to the child element.</p>
<pre><code class="lang-CSS"><span class="hljs-selector-id">#parentContainer</span> {
  <span class="hljs-attribute">display</span>: grid;
}
<span class="hljs-selector-id">#childContainer</span> {
  <span class="hljs-attribute">margin</span>: auto;
}
</code></pre>
<h2 id="heading-heres-the-result">Here's The Result</h2>
<p>Well as expected, following any of the above methods will result in this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot-2022-05-27-at-15.02.39.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we saw how to center a div using 10 different methods. Those methods were:</p>
<ol>
<li>Using <strong>position: relative</strong>, <strong>absolute</strong> and <strong>top</strong>, <strong>left</strong> offset values</li>
<li>Using <strong>position</strong>: <strong>relative</strong> and <strong>absolute</strong>, <strong>top</strong>, <strong>left</strong>, <strong>right</strong> and <strong>bottom</strong> offset values and <strong>margin: auto</strong></li>
<li>Using <strong>flexbox</strong>, <strong>justify-content</strong> and <strong>align-item</strong></li>
<li>Using <strong>flexbox</strong>, <strong>justify-content</strong> and <strong>align-self</strong></li>
<li>Using <strong>flexbox</strong> and <strong>margin: auto</strong></li>
<li>Using <strong>grid</strong>, <strong>justify-content</strong> and <strong>align-items</strong></li>
<li>Using <strong>grid</strong> and <strong>place-items</strong></li>
<li>Using <strong>grid</strong>, <strong>align-self</strong> and <strong>justify-self</strong></li>
<li>Using <strong>grid</strong> and <strong>place-self</strong></li>
<li>Using <strong>grid</strong> and <strong>margin: auto</strong></li>
</ol>
<p>We also looked at what all these properties like <code>justify-content</code>, <code>align-items</code>, <code>position</code> and so on meant and how we can use some of them together to center our divs.</p>
<h2 id="heading-some-good-resources">Some good resources</h2>
<ol>
<li><a target="_blank" href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">A Complete Guide to Flexbox</a></li>
<li><a target="_blank" href="https://css-tricks.com/snippets/css/complete-guide-grid/">A Complete Guide to Grid</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/css-flexbox-and-grid-tutorial/">Learn Flexbox and Grid by Building a Responsive Landing Page</a> </li>
</ol>
<h2 id="heading-github-link">GitHub link</h2>
<p>You can find the GitHub link for all the files for all the methods mentioned above here: <a target="_blank" href="https://github.com/sohamderoy/blog-setup-centring-divs">Github Link</a></p>
<h2 id="heading-wrap-up">Wrap Up</h2>
<p>Thanks for reading! I hope you liked this article on 10 different methods to center a <code>div</code> and I hope that they come handy to you in the future. </p>
<p>Do consider sharing this article with your friends – I'd really appreciate that. Stay tuned for more amazing content. Peace out! 🖖</p>
<h2 id="heading-social-links">Social Links</h2>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/feed/">LinkedIn</a></li>
<li><a target="_blank" href="https://www.sohamderoy.dev/">Website</a></li>
<li><a target="_blank" href="https://twitter.com/_sohamderoy">Twitter</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Higher Order Functions in JavaScript – Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, functions are treated as first-class citizens. We can treat functions as values and assign them to another variable, pass them as arguments to another function, or even return them from another function.  This ability of functions to a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/higher-order-functions-in-javascript/</link>
                <guid isPermaLink="false">66ba5d3de530197d3818e1a0</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham De Roy ]]>
                </dc:creator>
                <pubDate>Thu, 09 Jun 2022 19:59:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/Blog-8---Freecodecamp-Banner-new.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, functions are treated as first-class citizens. We can treat functions as values and assign them to another variable, pass them as arguments to another function, or even return them from another function. </p>
<p>This ability of functions to act as first-class functions is what powers higher order functions in JavaScript. </p>
<p>Basically, a function which takes another function as an argument or returns a function is known as a higher order function. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Group-35.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's deep dive a bit to see both types of implementation, that is:</p>
<ul>
<li>Passing a function as an argument to another function</li>
<li>Returning a function from another function</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/63eec0636ec9b999bf8c5ee5340dd54a_w200.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-pass-a-function-as-an-argument-to-another-function">How to Pass a Function as an Argument to Another Function</h2>
<p>In this section, we will see how we can send a function as an argument and ultimately how it helps us write cleaner code.</p>
<p>Consider the following code in which we want to create a function which accepts an array as an argument. It filters out all the odd numbers from it and returns all the filtered numbers. </p>
<p>The function will look something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>, <span class="hljs-number">11</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterOdd</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">const</span> filteredArr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    <span class="hljs-keyword">if</span> (arr[i] % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>) {
      filteredArr.push(arr[i]);
    }
  }
  <span class="hljs-keyword">return</span> filteredArr;
}
<span class="hljs-built_in">console</span>.log(filterOdd(arr));

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// [ 1, 3, 5, 7, 9, 11 ]</span>
</code></pre>
<p>The above function returns the filtered array <code>[ 1, 3, 5, 7, 9, 11 ]</code> where we have all the odd numbers, as expected.</p>
<p>Now let's say we also want to make a function that filters out and returns all the even numbers. We can very well go ahead and create the following function to achieve this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterEven</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">const</span> filteredArr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    <span class="hljs-keyword">if</span> (arr[i] % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>) {
      filteredArr.push(arr[i]);
    }
  }
  <span class="hljs-keyword">return</span> filteredArr;
}
<span class="hljs-built_in">console</span>.log(filterEven(arr));

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// [ 2, 4, 6, 8, 10 ]</span>
</code></pre>
<p>Again, as expected, we will get the desired output of an array with all even numbers in it – <code>[ 2, 4, 6, 8, 10 ]</code>. </p>
<p>But notice that we are writing a lot of duplicate code in this approach. Both the above functions do a lot of common things, like accepting the original array, creating a new array to store the filtered array, looping through the whole main array, and finally returning the filtered array. </p>
<p>The only difference between both functions is the logic they use to filter out the original array. </p>
<p>For the function <code>filterOdd</code> we use the logic of <code>arr[i] % 2 !== 0</code> whereas in the <code>filterEven</code> function we use the logic <code>arr[i] % 2 == 0</code> to filter out the original array. </p>
<p>This is where we can benefit from using higher order functions. The main intention is to create a function to do all the common stuff we did in the above two functions and pass the logic part separately as an argument to this function. Let's see how we can implement this.</p>
<p>Let's make the function which does all the common stuff we performed in the <code>filterOdd</code> and <code>filterEven</code> functions. This will go something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterFunction</span>(<span class="hljs-params">arr, callback</span>) </span>{
  <span class="hljs-keyword">const</span> filteredArr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) {
    callback(arr[i]) ? filteredArr.push(arr[i]) : <span class="hljs-literal">null</span>;
  }
  <span class="hljs-keyword">return</span> filteredArr;
}
</code></pre>
<p>Ignore the <code>callback</code> parameter for now. Notice how in the new <code>filterFuntion</code> we kept all the common steps, that is accepting the original array, creating a new array to store the filtered array, looping through the whole main array, and finally returning the filtered array that we were performing in the <code>filterOdd</code> and <code>filterEven</code> functions.</p>
<p>Now the <code>callback</code> parameter basically accepts the logic which will be nothing but another function containing the filtering logic. For filtering the odd and even numbers, respectively, here are the logic functions we need to write:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Function containing logic for filtering out odd numbers</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isOdd</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>;
}

<span class="hljs-comment">// Function containing logic for filtering out even numbers</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEven</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>;
}
</code></pre>
<p>That's it! We now just need to pass the main array, along with the logic function to our <code>filterFunction</code> like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// For filtering out odd numbers</span>

filterFunction(arr, isOdd)
<span class="hljs-comment">// Output of console.log(filterFunction(arr, isOdd)):</span>
<span class="hljs-comment">// [ 1, 3, 5, 7, 9, 11 ]</span>

<span class="hljs-comment">// For filtering out even numbers</span>

filterFunction(arr, isEven)
<span class="hljs-comment">// Output of console.log(filterFunction(arr, isEven)):</span>
<span class="hljs-comment">// [ 2, 4, 6, 8, 10 ]</span>
</code></pre>
<p>This way we are passing logic functions like <code>isOdd</code> or <code>isEven</code> as arguments to another function <code>filterFunction</code>. </p>
<p>We are basically abstracting out the main filtering logic from the main function. We can now pass any other filtering logic as we like to <code>filterFunction</code> without needing to change it.</p>
<p>For example, if we want to filter out a number greater than 5 then we just need to write the following filtering logic:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isGreaterThanFive</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x &gt; <span class="hljs-number">5</span>;
}
</code></pre>
<p>and pass it as an argument to <code>filterFunction</code>:</p>
<pre><code class="lang-javascript">filterFunction(arr, isGreaterThanFive)

<span class="hljs-comment">// Output of console.log(filterFunction(arr, isGreaterThanFive)):</span>
<span class="hljs-comment">// [ 6, 7, 8, 9, 10, 11 ]</span>
</code></pre>
<p>We can also pass the logic function as an arrow function and get the same result – that is, passing <code>(x) =&gt; x &gt; 5)</code> in place of <code>isGreaterThanFive</code> will give us the same result.</p>
<pre><code class="lang-javascript">filterFunction(arr, <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">5</span>)

<span class="hljs-comment">// Output of console.log(filterFunction(arr, (x) =&gt; x &gt; 5)):</span>
<span class="hljs-comment">// [ 6, 7, 8, 9, 10, 11 ]</span>
</code></pre>
<h3 id="heading-how-to-create-polyfills">How to Create Polyfills</h3>
<p>We know that JavaScript provides us with some inbuilt higher order functions like <code>map()</code>, <code>filter()</code>, <code>reduce()</code> and so on. Can we recreate our own implementation of these functions? Let's deep dive a little bit more.</p>
<p>We already created our filtering function in the above section. Let's create an array prototype of our <code>filterFunction</code> function so that we can use it with any array. This will look something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.prototype.filterFunction = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-keyword">const</span> filteredArr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    callback(<span class="hljs-built_in">this</span>[i]) ? filteredArr.push(<span class="hljs-built_in">this</span>[i]) : <span class="hljs-literal">null</span>;
  }
  <span class="hljs-keyword">return</span> filteredArr;
};
</code></pre>
<p>In the above code, <code>this</code> refers to the array the prototype is called upon. So if we write something like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
arr.filterFunction(callbackFn)
</code></pre>
<p>then <code>this</code> would refer to the array <code>arr</code>.</p>
<p>Now we can use the <code>filterFunction</code> just like we use the inbuilt <code>filter()</code> function in JS. We can write something like this:</p>
<pre><code class="lang-javascript">arr.filterFunction(isEven)
</code></pre>
<p>which is similar to calling the inbuilt <code>filter()</code> function:</p>
<pre><code class="lang-javascript">arr.filter(isEven)
</code></pre>
<p>Both the above function calls (that is <code>arr.filterFunction(isEven)</code> and <code>arr.filter(isEven)</code>) will give us same output, like <code>[ 2, 4, 6, 8, 10 ]</code>. </p>
<p>Similarly, we can also pass an arrow function in our prototype implementation as we can pass in the inbuilt <code>filter()</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// I</span>
arr.filterFunction(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>)
arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>)
<span class="hljs-comment">// both give the same output on console.log: [ 1, 3, 5, 7, 9, 11 ]</span>

<span class="hljs-comment">// II</span>
arr.filterFunction(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">5</span>)
arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">5</span>)
<span class="hljs-comment">// both give the same output on console.log: [ 6, 7, 8, 9, 10, 11 ]</span>
</code></pre>
<p>In a way, we have written a polyfill for the inbuilt <code>filter()</code> function.</p>
<h3 id="heading-function-chaining">Function Chaining</h3>
<p>We can also implement function chaining with our prototype implementation like we can with the inbuilt <code>filter()</code> function. Let's first filter out all the numbers greater than 5. Then from the result, we'll filter out all the even numbers. It will look something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using our own filterFunction() prototype implementation</span>
arr.filterFunction(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">5</span>).filterFunction(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>)

<span class="hljs-comment">//Using the inbuilt filter() implementation</span>
arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">5</span>).filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>)

<span class="hljs-comment">// both give the same output on console.log: [ 6, 8, 10 ]</span>
</code></pre>
<p>This is how we can use higher order functions in JS to write mode modular, cleaner and, more maintainable code.</p>
<p>Next, let's look at how we can return a function from another function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/lets-move-on-proceed.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-return-a-function-from-another-function-in-javascript">How to Return a Function from Another Function in JavaScript</h2>
<p>We can return a function from another function because we treat functions in JavaScript as values. Let's see this through an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span>(<span class="hljs-params">operation</span>) </span>{
  <span class="hljs-keyword">switch</span> (operation) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"ADD"</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${a}</span> + <span class="hljs-subst">${b}</span> = <span class="hljs-subst">${a + b}</span>`</span>);
      };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"SUBTRACT"</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${a}</span> - <span class="hljs-subst">${b}</span> = <span class="hljs-subst">${a - b}</span>`</span>);
      };
  }
}
</code></pre>
<p>In the above code, when we invoke the function <code>calculate</code> with an argument, it switches on that argument and then finally returns an anonymous function. So if we call the function <code>calculate()</code> and store its result in a variable and console log it, we will get the following output:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> calculateAdd = calculate(<span class="hljs-string">"ADD"</span>);
<span class="hljs-built_in">console</span>.log(calculateAdd);

<span class="hljs-comment">// Output: </span>
<span class="hljs-comment">// [Function (anonymous)]</span>
</code></pre>
<p>You can see that <code>calculateAdd</code> contains an anonymous function that the <code>calculate()</code> function returned.</p>
<p>There are two ways to call this inner function which we'll explore now.</p>
<h3 id="heading-call-the-returned-function-using-a-variable">Call the returned function using a variable</h3>
<p>In this method, we stored the return function in a variable as shown above and then invoked the variable to in turn invoke the inner function. </p>
<p>Let's see it in code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> calculateAdd = calculate(<span class="hljs-string">"ADD"</span>);
calculateAdd(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// Output: 2 + 3 = 5</span>


<span class="hljs-keyword">const</span> calculateSubtract = calculate(<span class="hljs-string">"SUBTRACT"</span>);
calculateSubtract(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// Output: 2 - 3 = -1</span>
</code></pre>
<p>So what'd we do here?</p>
<ul>
<li>We called the <code>calculate()</code> function and passed <code>ADD</code> as the argument</li>
<li>We stored the returned anonymous function in the <code>calculateAdd</code> variable, and </li>
<li>We invoked the inner returned function by calling <code>calculateAdd()</code> with the required arguments. </li>
</ul>
<h3 id="heading-call-the-returned-function-using-double-parentheses">Call the returned function using double parentheses</h3>
<p>This is a very sophisticated way of calling the inner returned function. We use double parentheses <code>()()</code> in this method. </p>
<p>Let's see it in code:</p>
<pre><code class="lang-javascript">calculate(<span class="hljs-string">"ADD"</span>)(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// Output: 2 + 3 = 5</span>

calculate(<span class="hljs-string">"SUBTRACT"</span>)(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// Output: 2 - 3 = -1</span>
</code></pre>
<p>You can thinks about this in a similar way to our chaining example above. It's just that instead of chaining functions, we chain the arguments. </p>
<p>The arguments in the first parentheses belong to the outer function, while the arguments in the second parentheses belong to the inner returned function. </p>
<p>The <code>calculate()</code> method returns a function as explained earlier, and it is that returned function which is immediately called using the second parentheses. </p>
<p>As I mentioned above, it's a very sophisticated way of calling a function. But once you get the hang of it, it becomes...well quite natural.</p>
<p>One place where we can see this kind of double parentheses notation is in the <code>connect</code> method in the <code>redux</code> state management library. You can read more about <code>connect</code> <a target="_blank" href="https://react-redux.js.org/api/connect">here</a>.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we learned: </p>
<ul>
<li>Why functions are called first class citizens in JS</li>
<li>What are higher order functions</li>
<li>How to pass a function as an argument to another function </li>
<li>How to create an array prototype, function chaining, writing our own polyfill for the inbuilt filter() method</li>
<li>How to return a function from another function and different ways to call the returned function</li>
</ul>
<h2 id="heading-wrapup">Wrapup</h2>
<p>Thanks for reading! I really hope you found this article on higher order functions useful. Stay tuned for more amazing content. Peace out! 🖖</p>
<h2 id="heading-social-links">Social Links</h2>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/feed/">LinkedIn</a></li>
<li><a target="_blank" href="https://www.sohamderoy.dev/">Website</a></li>
<li><a target="_blank" href="https://blog.sohamderoy.dev/">Blog site</a></li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/e2bd7ce3fc5f2783f1e210b015cc5fb1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
