<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[<DeveloperBlogs />]]></title><description><![CDATA[Hello folks!! 👋 I'm Anuradha Aggarwal, a software engineer who likes to explore new technologies, problem-solving, build projects 👩‍💻, and have a keen intere]]></description><link>https://anuradha.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 10 Sep 2026 23:50:48 GMT</lastBuildDate><atom:link href="https://anuradha.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[NPM v/s NPX]]></title><description><![CDATA[Hello Developers!! While working on any of your projects you might have come across NPM.
NPM stands for Node Package Manager and is a go to tool for managing NodeJS packages.

It helps you install libraries, manage dependencies & even define scripts ...]]></description><link>https://anuradha.hashnode.dev/npm-vs-npx</link><guid isPermaLink="true">https://anuradha.hashnode.dev/npm-vs-npx</guid><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[npm]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Wed, 03 Sep 2025 08:59:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756889808586/136854ef-d0c0-4bb6-bc02-cf94f2fae04c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Developers!! While working on any of your projects you might have come across NPM.</p>
<p><strong>NPM</strong> stands for <strong>Node Package Manager</strong> and is a go to tool for managing NodeJS packages.</p>
<ul>
<li>It helps you install libraries, manage dependencies &amp; even define scripts to automate tasks.</li>
</ul>
<p>Now switch to the term <strong>NPX</strong> which stands for <strong>Node Package Execute</strong></p>
<ul>
<li><p>it comes with the NPM, when you installed NPM above 5.2.0 version then automatically NPX will installed.</p>
</li>
<li><p>It is a NPM package runner that can execute any package that you want from the NPM registry without even installing that package.</p>
</li>
</ul>
<p>Let’s take a simple example to understand the difference between the two:</p>
<h1 id="heading-npm"><strong>🎯</strong> NPM</h1>
<h2 id="heading-example"><strong>📍</strong> Example</h2>
<p>Create a new directory</p>
<pre><code class="lang-bash">mkdir test-project
<span class="hljs-built_in">cd</span> test-project
</code></pre>
<p>Now install the package <code>cowsay</code> using NPM</p>
<pre><code class="lang-bash">npm install cowsay
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756885081863/d5c32662-a5eb-4ce5-bc5f-81c49a3e89d3.png" alt class="image--center mx-auto" /></p>
<p>Now if you check your project directory there will be new entry created inside the <code>node_modules</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756885236959/62978ba8-c2ac-4786-b8ff-f0ab52963339.png" alt class="image--center mx-auto" /></p>
<p>You can use this new package using that path like</p>
<pre><code class="lang-bash">./node_modules/.bin/cowsay hello
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756885379165/ec19bfe4-dd87-4c86-8edd-c8814cc465ce.png" alt class="image--center mx-auto" /></p>
<p>Or instead of using the whole path, directly use the package name like</p>
<pre><code class="lang-bash">cowsay world
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756885444696/987504f3-9817-496e-aca5-626c4a711bfc.png" alt class="image--center mx-auto" /></p>
<p>So now you understand whenever we use NPM for any package update you have to install it which will occupy space in your system.</p>
<h2 id="heading-usage"><strong>📍</strong> Usage</h2>
<ul>
<li><p>You are working on a long-term project where you’ll frequently use the same packages and libraries.</p>
</li>
<li><p>You want to <strong>manage dependencies</strong> and ensure they are tracked in your package.json.</p>
</li>
</ul>
<h1 id="heading-npx"><strong>🎯</strong> NPX</h1>
<h2 id="heading-example-1"><strong>📍</strong> Example</h2>
<p>It is a <strong>NPM Package Executor</strong> that can execute any package that you want from the NPM registry without even installing that package.</p>
<p>Let’s try this out:</p>
<pre><code class="lang-bash">mkdir test-npx
<span class="hljs-built_in">cd</span> test-npx

npx cowsay hello
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756887321943/5fd59638-dd00-4542-8f8d-e1641232d392.png" alt class="image--center mx-auto" /></p>
<p>Also if you check <code>test-npx</code> directory, it is empty that means this package does not occupy any space.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756887463879/a72cf441-f489-4d8a-b262-b50d83b2b7b4.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-usage-1"><strong>📍</strong> Usage</h2>
<ul>
<li><p>You want to <strong>execute a package</strong> without permanently installing it.</p>
</li>
<li><p>You’re running one-off commands like create-react-app, eslint, or package binaries.</p>
</li>
<li><p>You need to run a specific <strong>version</strong> of a package or command without modifying your existing setup.</p>
</li>
</ul>
<h1 id="heading-wrap-up"><strong>🎯 Wrap Up!!</strong></h1>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/Anuradh06359394"><strong>Twitter</strong></a> <a target="_blank" href="https://www.instagram.com/blogcode404/"><strong>Instagram</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[Building Your First CLI Tool]]></title><description><![CDATA[Hello developers!! You must have use multiple CLI tools in your everyday development like echo, ls, cd etc.
Let’s try to understand it in a better way by creating your own simple CLI tool.
In this article, we will create a simple Calculator CLI tool....]]></description><link>https://anuradha.hashnode.dev/building-your-first-cli-tool</link><guid isPermaLink="true">https://anuradha.hashnode.dev/building-your-first-cli-tool</guid><category><![CDATA[cli]]></category><category><![CDATA[cli tool]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Developer Tools]]></category><category><![CDATA[terminal]]></category><category><![CDATA[development]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 24 Aug 2025 14:03:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756043983147/05b26052-1ab2-4d9b-8fab-baf52a0e0e5d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello developers!! You must have use multiple CLI tools in your everyday development like <code>echo</code>, <code>ls</code>, <code>cd</code> etc.</p>
<p>Let’s try to understand it in a better way by creating your own simple CLI tool.</p>
<p>In this article, we will create a simple Calculator CLI tool.</p>
<h2 id="heading-what-is-cli-tool"><strong>🎯</strong> What is CLI Tool?</h2>
<p>A <strong>CLI (Command Line Interface) tool</strong> is just a <strong>program you run in the terminal</strong> by typing commands with your keyboard, instead of clicking buttons in a GUI (Graphical User Interface).</p>
<h2 id="heading-project-setup"><strong>🎯</strong> Project Setup</h2>
<ol>
<li>Setup the Project with initial command</li>
</ol>
<pre><code class="lang-bash">npm init
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755986386536/a569e630-d344-4212-978f-6b51a950d636.png" alt class="image--center mx-auto" /></p>
<ol start="2">
<li><p>Create a folder named <code>src</code> in the root directory of your project.</p>
</li>
<li><p>Inside <code>src</code> create a file called <code>index.js</code> This is going to be the entry point of our CLI.</p>
</li>
<li><p>In the <code>package.json</code> file, change the <strong>“main”</strong> part to <code>src/index.js</code>.</p>
</li>
<li><p>Now manually add another entry into the <code>package.json</code> file called <code>bin</code> and set its key to <code>calc</code> and it's value to <code>./src/index.js</code>.</p>
</li>
</ol>
<p>Your resultant <code>package.json</code> file would look like this:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"calculator-cli-tool"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-string">"description"</span>: <span class="hljs-string">"A CLI tool used for calculations"</span>,
  <span class="hljs-string">"main"</span>: <span class="hljs-string">"src/index.js"</span>,
  <span class="hljs-string">"bin"</span>: {
    <span class="hljs-string">"calc"</span>: <span class="hljs-string">"./src/index.js"</span>
  },
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-string">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-string">"license"</span>: <span class="hljs-string">"ISC"</span>
}
</code></pre>
<p>The key <code>calc</code>, is the <strong>keyword for calling the CLI</strong>. This is the keyword that user will type in the terminal for using your CLI.</p>
<h2 id="heading-commander"><strong>🎯</strong> Commander</h2>
<ul>
<li><p>Commander is a <strong>popular Node.js library</strong> that makes it easy to build <strong>CLI tools</strong>.</p>
</li>
<li><h3 id="heading-what-commander-gives-you">What <code>commander</code> gives you?</h3>
<ol>
<li><p><strong>Commands</strong> → Define sub-commands like <code>add</code>, <code>multiply</code>.</p>
</li>
<li><p><strong>Arguments</strong> → Easily get values like <code>5 7</code>.</p>
</li>
<li><p><strong>Options (flags)</strong> → Support things like <code>--verbose</code> or <code>--format json</code>.</p>
</li>
<li><p><strong>Automatic help</strong> → Generates <code>--help</code> output for free.</p>
</li>
<li><p><strong>Versioning</strong> → Add <code>--version</code> easily.</p>
</li>
</ol>
</li>
</ul>
<p>Let’s install <a target="_blank" href="https://www.npmjs.com/package/commander">commander</a>:</p>
<pre><code class="lang-bash">npm install commander
</code></pre>
<p>In <code>src/index.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-meta">#!/usr/bin/env node</span>
<span class="hljs-keyword">const</span> { Command } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'commander'</span>);
<span class="hljs-keyword">const</span> program = <span class="hljs-keyword">new</span> Command();

program
  .name(<span class="hljs-string">'calc'</span>)
  .description(<span class="hljs-string">'A simple calculator CLI'</span>)
  .version(<span class="hljs-string">'1.0.0'</span>);

<span class="hljs-comment">// Command: add</span>
program
  .command(<span class="hljs-string">'add &lt;a&gt; &lt;b&gt;'</span>)
  .description(<span class="hljs-string">'Add two numbers'</span>)
  .action(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Number</span>(a) + <span class="hljs-built_in">Number</span>(b));
  });

<span class="hljs-comment">// Command: multiply</span>
program
  .command(<span class="hljs-string">'multiply &lt;a&gt; &lt;b&gt;'</span>)
  .description(<span class="hljs-string">'Multiply two numbers'</span>)
  .option(<span class="hljs-string">'-v, --verbose'</span>, <span class="hljs-string">'Show detailed steps'</span>)
  .action(<span class="hljs-function">(<span class="hljs-params">a, b, options</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> result = <span class="hljs-built_in">Number</span>(a) * <span class="hljs-built_in">Number</span>(b);
    <span class="hljs-keyword">if</span> (options.verbose) {
      <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">${result}</span>`</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(result);
    }
  });

program.parse();
</code></pre>
<h2 id="heading-link-it-globally"><strong>🎯</strong> Link it globally</h2>
<p>Now if you run the below command in your project folder, this creates a <strong>global symlink</strong> so you can use <code>calc</code> anywhere.</p>
<pre><code class="lang-bash">npm link
</code></pre>
<p>Now your CLI tool is ready to use anywhere in your system. Let’s try it now:</p>
<h2 id="heading-cli-building-blocks"><strong>🎯</strong> CLI Building Blocks</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1756020163783/36127e10-e577-415a-8e9b-043a97899fb5.png" alt class="image--center mx-auto" /></p>
<p>As you noticed in the above examples, there are multiple parts in the single commands, let’s break it down.</p>
<ul>
<li><p><code>calc</code> is the <strong>main command</strong> (the tool itself).</p>
</li>
<li><p><code>add</code>, <code>multiply</code> represents <strong>sub-command</strong> (an action inside <code>calc</code>).</p>
</li>
<li><p><code>5</code>, <code>7</code> represents the <strong>arguments</strong> (values you pass)</p>
</li>
<li><p><code>—verbose</code> is a <strong>option</strong> which acts like a flag &amp; modifies behavior</p>
</li>
</ul>
<h2 id="heading-wrap-up"><strong>🎯 Wrap Up!!</strong></h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/Anuradh06359394"><strong>Twitter</strong></a> <a target="_blank" href="https://www.instagram.com/blogcode404/"><strong>Instagram</strong></a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[React Design Patterns]]></title><description><![CDATA[Hello developers!! While developing apps in React, I'm sure you have come across different use cases which cannot be easy to solve using the same older approach.
Each use cases demand a different pattern to solve the problem in the most optimised way...]]></description><link>https://anuradha.hashnode.dev/react-design-patterns</link><guid isPermaLink="true">https://anuradha.hashnode.dev/react-design-patterns</guid><category><![CDATA[React]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[components in react]]></category><category><![CDATA[design and architecture]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 09 Jul 2023 16:30:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688920083612/e0fe9a93-f0f6-4870-b2ce-d9a012379d51.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello developers!! While developing apps in React, I'm sure you have come across different use cases which cannot be easy to solve using the same older approach.</p>
<p>Each use cases demand a different pattern to solve the problem in the most optimised way and also made our code more scalable.</p>
<p>React provides different design patterns to solve common problems. The list of commonly used design patterns in React are:</p>
<ul>
<li><p>Presentational &amp; Container Component</p>
</li>
<li><p>Higher Order Components</p>
</li>
<li><p>Render Props</p>
</li>
<li><p>Compound Components</p>
</li>
<li><p>Hooks</p>
</li>
</ul>
<p>Let's explore them one by one.</p>
<h3 id="heading-1-presentational-andamp-container-component"><strong>🎯</strong> 1. Presentational &amp; Container Component</h3>
<p>Each component in React has two parts: One is logic to handle your data and the other is displaying data on screen.</p>
<p>This pattern helps <strong>separate concerns</strong> by splitting components into two categories. <strong>Container components</strong> handle the logic and state management, while <strong>Presentational components</strong> focus on rendering the UI based on the provided props.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> DisplayList = <span class="hljs-function">(<span class="hljs-params">{ patientRecord }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {patientRecord.map((patient, id) =&gt; {
        return <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{id}</span>&gt;</span>{patient}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>;
      })}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
};
</code></pre>
<p>Container components, on the other hand, keep track of the internal states and data-fetching logic and handles business logic.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> PatientComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [patientList, getPatientList] = React.useState([]);

  React.useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Fetch data through an API and apply business logic</span>
    (<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetchPatientList();

      setPatientList([...response]);
    })()
  }, []);

  <span class="hljs-comment">// provide data to presentational component to display</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DisplayList</span> <span class="hljs-attr">patientRecord</span>=<span class="hljs-string">{patientList}</span> /&gt;</span></span>; 
};
</code></pre>
<p>The container component passes the state and any required callbacks as props to the presentational component. The presentational component is responsible for rendering the UI based on the provided props, without worrying about the data fetching or business logic.</p>
<h3 id="heading-2-higher-order-components"><strong>🎯</strong> 2. Higher Order Components</h3>
<p>HOCs take one component as an input and give a newly created component with additional functionalities as an output. It allows you to reuse component logic by wrapping components with additional functionality.</p>
<p>By using HOCs, we can easily add common functionality to multiple components without duplicating code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withLogging</span>(<span class="hljs-params">WrappedComponent</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">WithLogging</span>(<span class="hljs-params">props</span>) </span>{
    React.useEffect(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Component <span class="hljs-subst">${WrappedComponent.name}</span> mounted`</span>);
      <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Component <span class="hljs-subst">${WrappedComponent.name}</span> unmounted`</span>);
      };
    }, []);

    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">WrappedComponent</span> {<span class="hljs-attr">...props</span>} /&gt;</span></span>;
  };
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>My Component<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};

<span class="hljs-keyword">const</span> EnhancedComponent = withLogger(MyComponent);
</code></pre>
<p>In the example above, <code>withLogger</code> is a HOC that takes a component (<code>WrappedComponent</code>) as input and returns a new component (<code>WithLogger</code>). The returned component logs a message to the console when it mounts and unmounts.</p>
<p>To use the HOC, we wrap our original component <code>MyComponent</code> with <code>withLogger</code>, creating a new component <code>EnhancedComponent</code>. The enhanced component has the same functionality as <code>MyComponent</code>, but it also includes the logging behaviour defined in the HOC.</p>
<h3 id="heading-3-render-props"><strong>🎯</strong> 3. Render props</h3>
<p>In this pattern, a component receives a function as a prop and uses that function to render its content.</p>
<pre><code class="lang-javascript"><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> MouseTracker = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [position, setPosition] = React.useState({ <span class="hljs-attr">x</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">0</span> });

  <span class="hljs-keyword">const</span> handleMouseMove = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setPosition({ <span class="hljs-attr">x</span>: event.clientX, <span class="hljs-attr">y</span>: event.clientY });
  };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onMouseMove</span>=<span class="hljs-string">{handleMouseMove}</span>&gt;</span>{props.renderPosition(position)}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> DisplayMousePosition = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MouseTracker</span>
    <span class="hljs-attr">renderPosition</span>=<span class="hljs-string">{({</span> <span class="hljs-attr">x</span>, <span class="hljs-attr">y</span> }) =&gt;</span> (
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        Mouse position: {x}, {y}
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    )}
  /&gt;</span>
);
</code></pre>
<p>A prop like <code>renderPosition</code> is called a <strong><em>render prop</em></strong> because it is a prop that specifies how to render a piece of the user interface.</p>
<h3 id="heading-4-compound-components"><strong>🎯</strong> 4. Compound Components</h3>
<p>Compound components are a pattern used in React to create components that work together as a group, allowing users to customize and control the rendering of multiple related components.</p>
<p>It allows you to define a parent component that encapsulates the behaviour and state of child components, while still giving flexibility to users to determine the composition and appearance of the child components.</p>
<p>Let's consider a use case where you need to create a <strong>List component</strong> in React which looks something like an unordered list in native HTML or an Accordion component.</p>
<pre><code class="lang-javascript">&lt;List&gt;
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span>
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span>  
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span>
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>4<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span> 
&lt;/List&gt;
</code></pre>
<p>Now in this scenario, we need some of the states of the <strong>List</strong> component to be transferred to its child component i.e. <strong>ListItem.</strong> It can be implemented either by using the <code>context API</code> or <code>React.cloneElement</code> API.</p>
<p>Let's explore how to develop the same scenario using <strong>Context API</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ListContext = React.createContext();
<span class="hljs-keyword">const</span> { Provider } = ListContext;

<span class="hljs-comment">// Parent Component</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> List = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { children, size } = props;

  <span class="hljs-keyword">const</span> sharedProp = { size }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{sharedProp}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        {children}
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>  
    <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
  )
}

<span class="hljs-comment">// Child Component</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ListItem = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> contextProp = React.useContext(ListContext);
  <span class="hljs-keyword">const</span> { size } = contextProp;

  <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{size</span> === <span class="hljs-string">'medium'</span> ? <span class="hljs-attr">bg-primary</span> <span class="hljs-attr">:</span> <span class="hljs-attr">bg-secondary</span>}&gt;</span>
      {props.children}
   <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  )
}

<span class="hljs-comment">// Usage</span>
&lt;List size=<span class="hljs-string">'medium'</span>&gt;
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>Item 1<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span>
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>Item 2<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span>
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ListItem</span>&gt;</span>Item 3<span class="hljs-tag">&lt;/<span class="hljs-name">ListItem</span>&gt;</span></span>
&lt;/List&gt;
</code></pre>
<p>In the above example, React Context is created to share the prop <code>size</code> between the parent (&lt;<strong>List&gt;</strong>) and child (<strong>&lt;ListItem&gt;</strong>) components. Also, the user has the flexibility to provide custom content inside each list item.</p>
<h3 id="heading-5-hooks"><strong>🎯</strong> 5. Hooks</h3>
<p>Hooks are introduced in React Functional component as a replacement for Class components. There are multiple hooks available to manage states and different lifecycle methods of React.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>
  )
}
</code></pre>
<p>We can also create custom hooks to solve our specific use case and code reusability.</p>
<p>You can read about the most commonly used built-in react hooks <a target="_blank" href="https://react.dev/reference/react">here</a>.</p>
<h3 id="heading-wrap-up"><strong>🎯</strong> Wrap Up!!</h3>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/Anuradh06359394"><strong>Twitter</strong></a> <a target="_blank" href="https://www.instagram.com/blogcode404/"><strong>Instagram</strong></a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Configuration v/s Composition - Design Reusable Components]]></title><description><![CDATA[Hello folks!! In this article, we'll learn about how to design component APIs for your design system and make it reusable across different teams, fulfilling all the use cases in the most optimised way and following the design principles guidelines.
W...]]></description><link>https://anuradha.hashnode.dev/configuration-vs-composition-design-reusable-components</link><guid isPermaLink="true">https://anuradha.hashnode.dev/configuration-vs-composition-design-reusable-components</guid><category><![CDATA[Design Systems]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[React]]></category><category><![CDATA[design and architecture]]></category><category><![CDATA[design principles]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Thu, 29 Jun 2023 17:03:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688058060452/70e566eb-fa1b-4fb1-b07f-bfd5bb0f7350.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello folks!! In this article, we'll learn about how to design component APIs for your design system and make it reusable across different teams, fulfilling all the use cases in the most optimised way and following the design principles guidelines.</p>
<p>We'll look into the different approaches to building component APIs.</p>
<h2 id="heading-component-requirements"><strong>🎯</strong> Component Requirements</h2>
<p>While building a component, we'll consider into mind the different use cases and as we add more functionality, the complexity of components increases. So before building future-proof components let's first explore all the use cases:</p>
<p>Consider creating an <strong>Alert</strong> component which looks something similar to this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687625535961/97aa8fb2-d1e6-4868-bb44-9f81ecd52d1d.png" alt class="image--center mx-auto" /></p>
<p>Let's first break down the entire component into smaller subcomponents.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688024154286/3497ce4e-643c-441b-bed9-973af265fada.png" alt class="image--center mx-auto" /></p>
<p>The <strong>Alert</strong> component consists of the following subparts:</p>
<ol>
<li><p><strong>Title</strong></p>
<p> It can be a <code>string</code> or may be optional</p>
</li>
<li><p><strong>Message</strong></p>
<p> Message can consist of multiline text or any other component. So we can fix its type to <code>string | ReactNode</code></p>
</li>
<li><p><strong>Action buttons</strong></p>
<p> It consists of any component where input from the user is required. It may consist of multiple buttons, or any other component or might be an optional field.</p>
<p> Its type is set to <code>ReactNode | undefined</code></p>
</li>
<li><p><strong>Icon</strong></p>
<ul>
<li><p>We can define any icon to be shown.</p>
</li>
<li><p>Along with the icon name, its position also matters. There might be a case when we need to show the icon to the right.</p>
</li>
<li><p>The icon can also vary based on size.</p>
</li>
</ul>
</li>
<li><p><strong>Variants</strong></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688034492303/caaed915-383f-4c06-a1d6-cbd24d1e02ed.png" alt class="image--center mx-auto" /></p>
<p> The alert component can come under multiple variants and based on the type of variants colours, the font style of its subparts (title, message, icon) changes.</p>
</li>
<li><p><strong>Patterns</strong></p>
<p> As some of the subparts are optional in the Alert component and the user can also add its custom component, this will result in multiple patterns.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688035513460/a3b6b2f8-d969-4e2f-9fe0-41645c98aacf.png" alt class="image--center mx-auto" /></p>
<p> Now that we had go through all the requirements, let's move to the code part.</p>
</li>
</ol>
<h2 id="heading-configuration"><strong>🎯</strong> Configuration</h2>
<blockquote>
<p>In the Configuration approach, the user can pass data to the component via props, and the component should know exactly how to render itself based on that props.</p>
</blockquote>
<p>Let's move with the above example of the Alert component and see how to design its API using a configuration approach.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Alert = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> {
        title,
        description,
        actions,
        iconName, 
        iconSize, 
        iconPosition=<span class="hljs-string">'left'</span>, 
        iconColor, 
        variant 
    } = props;

    <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">{variantClass}</span>&gt;</span>
          {iconName &amp;&amp; 
            <span class="hljs-tag">&lt;<span class="hljs-name">Icon</span> 
              <span class="hljs-attr">name</span>=<span class="hljs-string">{iconName}</span> 
              <span class="hljs-attr">size</span>=<span class="hljs-string">{iconSize}</span> 
              <span class="hljs-attr">position</span>=<span class="hljs-string">{iconPosition}</span> 
              <span class="hljs-attr">appearance</span>=<span class="hljs-string">{iconColor}</span> 
            /&gt;</span>
          }
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            {title &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">Heading</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">Heading</span>&gt;</span>}
            {message &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">Paragraph</span>&gt;</span>{description}<span class="hljs-tag">&lt;/<span class="hljs-name">Paragraph</span>&gt;</span>}
            {actions &amp;&amp; (
              <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{actions}<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">div</span>&gt;</span></span>

    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Alert;
</code></pre>
<p>Users can use this component using the following API:</p>
<pre><code class="lang-javascript">&lt;Alert 
  title=<span class="hljs-string">'Title goes here'</span>
  description=<span class="hljs-string">'Message goes here'</span>
  variant=<span class="hljs-string">'warning'</span>
  iconName=<span class="hljs-string">'warning_check'</span>
  iconPosition=<span class="hljs-string">'right'</span>  
  actions={
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Action 1<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Action 2<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>
  }
/&gt;
</code></pre>
<p>As you notice, for all the functionality user needs to pass a prop to the component but all the design decision and rendering is handled internally by the component.</p>
<h3 id="heading-pros">📍 Pros:</h3>
<ul>
<li><p>Quick and easy to use. Different functionality and visual variants can be controlled by configuring props.</p>
</li>
<li><p>Configuration API via props makes it harder to diverge from the design system and keeps the UI and behaviour consistent.</p>
</li>
</ul>
<h3 id="heading-cons">📍 Cons:</h3>
<ul>
<li><p>Adding more features requires more props and conditional logic. Thus a component becomes harder to maintain.</p>
</li>
<li><p>Not easy to extend.</p>
</li>
<li><p>Not easy to override</p>
</li>
<li><p>If a component can't be extended, a new version might need to be built.</p>
</li>
</ul>
<p>Using the above approach, the user does not need to worry about the design consistency across the app, they simply need to pass the prop to the component and all the design and visual aspects need to be handled by the component internally.</p>
<p>But it may be overhead as sometimes props provided by the component are not enough to satisfy all the use cases and the user may want some kind of customisation. Also for each functionality providing a different prop may to lead complex APIs which are not easy to extend.</p>
<p>Let's explore another approach for a similar use case.</p>
<h2 id="heading-composition"><strong>🎯</strong> Composition</h2>
<blockquote>
<p>In the Composition approach, Users should be able to take small building blocks and combine them together in whatever order they like.</p>
</blockquote>
<p>Using this approach, the user is provided with multiple subcomponents which can be used in whatever order as per their use cases. Let's look at an example for better understanding.</p>
<pre><code class="lang-javascript">
&lt;Alert variant=<span class="hljs-string">'warning'</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Alert.Container</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Alert.Title</span>&gt;</span>
            Title goes here
        <span class="hljs-tag">&lt;/<span class="hljs-name">Alert.Title</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Alert.Description</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello World!!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Badge</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">Badge</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Paragraph</span>&gt;</span>Short Description<span class="hljs-tag">&lt;/<span class="hljs-name">Paragraph</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Alert.Description</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Alert.Action</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">Button</span>&gt;</span>Action 1<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Action 2<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">Alert.Action</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Alert.Icon</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'warning_check'</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Alert.Container</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">Alert</span>&gt;</span></span>
</code></pre>
<p>In the above code, instead of passing multiple props, the user can use smaller subcomponents for customisation. For example, Instead of passing a description as a <code>string</code> they can also pass a custom-designed description as per their use case. And also change the position of the icon to the right.</p>
<p>All these are just building blocks which are used to <strong>compose</strong> the functionality based on different use cases.</p>
<h3 id="heading-pros-1">📍 Pros:</h3>
<ul>
<li><p>Extremely flexible</p>
</li>
<li><p>It's easy to create different functionality and UI variants and add new building blocks.</p>
</li>
<li><p>Makes a component library much more resistant to change</p>
</li>
</ul>
<h3 id="heading-cons-1">📍 Cons:</h3>
<ul>
<li><p>You need to compose the building blocks yourself to create a fully functioning component/feature.</p>
</li>
<li><p>Takes more time and code.</p>
</li>
<li><p>It's easy to diverge from the design system and ship inconsistent UI and behaviour.</p>
</li>
</ul>
<h2 id="heading-which-approach-to-use"><strong>🎯</strong> Which Approach to use?</h2>
<p>Both approaches as we see above have their advantages and disadvantages. Then the question is which one to use and when?</p>
<p>The approach you want to use totally depends on your use case and design pattern. There might be cases when we can use both approaches to satisfy our use case appropriately.</p>
<h2 id="heading-summary"><strong>🎯</strong> Summary</h2>
<p>The <strong>Composition</strong> approach offers more flexibility, but it does require more knowledge of how to compose the building blocks and how they work.</p>
<p>On the other hand, the <strong>Configuration</strong> approach is less flexible, but it is simpler to use and makes it easier to stick to the design system.</p>
<h2 id="heading-wrap-up"><strong>🎯</strong> Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/Anuradh06359394"><strong>Twitter</strong></a> <a target="_blank" href="https://www.instagram.com/blogcode404/"><strong>Instagram</strong></a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Role of Service Worker In PWAs]]></title><description><![CDATA[Hello Folks!! In the previous article, we learnt about service workers and their lifecycles. In this article let's see service workers in practice.

🎯 Register a Service Worker
Create a service worker and register it in a browser from another javasc...]]></description><link>https://anuradha.hashnode.dev/role-of-service-worker-in-pwas</link><guid isPermaLink="true">https://anuradha.hashnode.dev/role-of-service-worker-in-pwas</guid><category><![CDATA[Service Workers]]></category><category><![CDATA[progressive web apps]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[app development]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 18 Jun 2023 17:59:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687111047537/051624a4-baaa-4832-864f-53c2d388f7ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Folks!! In the previous article, we learnt about <a target="_blank" href="https://anuradha.hashnode.dev/service-workers">service workers</a> and their lifecycles. In this article let's see service workers in practice.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687025991673/b2acaa3a-2ff8-422f-a2d7-0f8fdd74afc7.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-register-a-service-worker"><strong>🎯</strong> Register a Service Worker</h2>
<p>Create a service worker and register it in a browser from another javascript file.</p>
<p>In file <code>js/app.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Step 1: register a service worker</span>
<span class="hljs-keyword">if</span>(<span class="hljs-string">'serviceWorker'</span> <span class="hljs-keyword">in</span> navigator){
  navigator.serviceWorker.register(<span class="hljs-string">'/sw.js'</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">reg</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Service Worker Registered'</span>, reg))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error in Registering Service Worker'</span>, err))
}
</code></pre>
<ul>
<li><p>First, we will check if the browser supports the service worker or not.</p>
</li>
<li><p><code>navigator</code> is an object in javascript that represents the browser and information about it.</p>
</li>
<li><p>In <code>register</code> method we need to provide the path to our service worker file.</p>
</li>
</ul>
<p>Now you can check the result in the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685813347618/5dc045b4-e55e-41e6-91e4-ec409fe06361.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685813525795/870ca21a-bf03-4b6d-8731-572acb9b9c0d.png" alt class="image--center mx-auto" /></p>
<p><strong>Points to remember:</strong></p>
<ul>
<li>Service workers only work on pages where they're served over a secure HTTPS connection. Also, localhost is an exception so that we can easily develop an app using service workers.</li>
</ul>
<h2 id="heading-install-event"><strong>🎯</strong> Install Event</h2>
<p>The browser emits the install event automatically while the service worker is being installed. So we can listen to that install event.</p>
<p>Create a new file <code>sw.js</code> in the root directory so that it has access to the overall scope.</p>
<p>In file <code>sw.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> staticCacheName = <span class="hljs-string">"site-static-v2"</span>;
<span class="hljs-keyword">const</span> assets = [
  <span class="hljs-string">"/"</span>,
  <span class="hljs-string">"/index.html"</span>,
  <span class="hljs-string">"/js/app.js"</span>,
  <span class="hljs-string">"/css/styles.css"</span>,
  <span class="hljs-string">"https://unpkg.com/@innovaccer/design-system@2.15.3/css/dist/index.css"</span>,
  <span class="hljs-string">"https://fonts.googleapis.com/css?family=Nunito+Sans:300,300i,400,400i,600,600i,700,700i,800,800i,900,900i&amp;display=swap"</span>,
  <span class="hljs-string">"https://fonts.gstatic.com/s/nunitosans/v12/pe03MImSLYBIv1o4X1M8cc8GBs5tU1ECVZl_.woff2"</span>,
  <span class="hljs-string">"/pages/404.html"</span>
];

<span class="hljs-comment">// Step 2: Install Service Worker</span>
self.addEventListener(<span class="hljs-string">"install"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"service worker has been installed!!"</span>);
  event.waitUntil(
    caches.open(staticCacheName).then(<span class="hljs-function">(<span class="hljs-params">cache</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"caching shell assets"</span>);
      cache.addAll(assets);
    })
  );
});
</code></pre>
<ul>
<li><p><code>self</code> inside a service worker refers to the service worker itself.</p>
</li>
<li><p>This event will occur only when we first install it or any changes in the file have been made.</p>
</li>
<li><p>We can use this event to add common assets to the cache so that users can still see those assets in the offline mode.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685815529787/ca6f2146-4151-418b-942e-003ff17f4f6e.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-activate-event"><strong>🎯</strong> Activate Event</h2>
<p>When the service worker is installed it becomes active. Once the service worker is active, it can access all the different pages and all the different files <strong>inside its scope.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> clearOldCaches = <span class="hljs-function">() =&gt;</span>
  caches.keys().then(<span class="hljs-function">(<span class="hljs-params">keys</span>) =&gt;</span>
    <span class="hljs-built_in">Promise</span>.all(
      keys
        .filter(<span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> key !== staticCacheName &amp;&amp; key !== dynamicCacheName)
        .map(<span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"[sw] remove cache"</span>, key);
          caches.delete(key);
          <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        })
    )
  );

<span class="hljs-comment">// Step 3: Activate Service Worker</span>
self.addEventListener(<span class="hljs-string">"activate"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"service worker has been activated!!"</span>);

  event.waitUntil(clearOldCaches());
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686507245679/d15a86ee-9c10-41af-8c9a-988c487b52b0.png" alt class="image--center mx-auto" /></p>
<p>The service worker will wait to activate until all the instances of the app will be closed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685820027118/3714c64c-98bd-48d4-b6dc-fbd218ec0e42.png" alt class="image--center mx-auto" /></p>
<p>But it is a bit tedious as we have to first close all the tabs on which our app is running and then it reinstalls and comes under the running state. To avoid this we can use the following approaches:</p>
<ul>
<li><p>use the <code>skipWaiting</code> option.</p>
</li>
<li><p>use <code>Update on reload</code> option.</p>
</li>
</ul>
<h2 id="heading-fetch-event"><strong>🎯</strong> Fetch Event</h2>
<p>The fetch event occurs whenever we try to get something from a server like any CSS file or javascript file.</p>
<p>We have <code>index.html</code> file running in the browser which was initially fetched from a server. When an app requests a stylesheet or images or some other page it sends a request from the browser to the server and in response gets the requested resources.</p>
<p>We also have a service worker in the background listening for any fetch requests from our app. This service worker <strong>acts as a proxy</strong> between our app and a server.</p>
<p>Now whenever we make any request for resources it goes through the service worker and at this point, a fetch event is emitted and the service worker can listen for and react to it. We can either intercept the request or sent a custom response.</p>
<p>Service workers <strong>handle the cached asset</strong> and while making a fetch request we can prevent to sent the request directly to the server and instead send cached resources.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686505981711/26204719-57ea-440a-b085-5f7b6794a7c2.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript">self.addEventListener(<span class="hljs-string">"fetch"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.respondWith(
    (<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> r = <span class="hljs-keyword">await</span> caches.match(e.request);
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`[Service Worker] Fetching resource: <span class="hljs-subst">${e.request.url}</span>`</span>);
      <span class="hljs-keyword">if</span> (r) {
        <span class="hljs-keyword">return</span> r;
      }
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(e.request);
      <span class="hljs-keyword">const</span> cache = <span class="hljs-keyword">await</span> caches.open(dynamicCacheName);
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`[Service Worker] Caching new resource: <span class="hljs-subst">${e.request.url}</span>`</span>);
      cache.put(e.request, response.clone());
      <span class="hljs-keyword">return</span> response;
    })()
  );
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686507336368/cf807e17-ef5f-4896-bc0e-adbe6231e74c.png" alt class="image--center mx-auto" /></p>
<p>Now we have seen all the lifecycle events of the service worker. A service worker is one of the steps in creating a Progressive web app. Let's see how to audit your application.</p>
<h2 id="heading-lighthouse-audit"><strong>🎯</strong> Lighthouse Audit</h2>
<p>Chrome dev tools give us a way to audit our application using the lighthouse plugin which provides us with a checklist of required actions to make a site a valid PWA.</p>
<p>Go to the <code>Lighthouse</code> tab in Chrome dev tools and check the Progressive Web App option and press the <strong>Analyze page load</strong> button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686708863966/5476e9c7-19ce-4036-b95e-d86f0b1a047f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686709031454/23194eaa-e09c-4545-99c7-640dbd84e425.png" alt class="image--center mx-auto" /></p>
<p>It provides us with the checklists to complete to create a valid PWA.</p>
<h2 id="heading-install-prompt"><strong>🎯 Install Prompt</strong></h2>
<p>We can also get an 'Install Banner' in our app by fulfilling certain criteria. This banner is similar to <strong>Add to home screen</strong> option which allows us to install the application into our device.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686709780989/ee3d7e1d-609f-4955-8a36-ff429c72fb6e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686709894702/aef6e424-5f2b-47df-a58a-4ef417a09df0.png" alt class="image--center mx-auto" /></p>
<p>We can check all the criteria to show the install banner on this <a target="_blank" href="https://developer.chrome.com/blog/app-install-banners-native/">site</a>.</p>
<h2 id="heading-wrap-up"><strong>🎯 Wrap Up!!</strong></h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/Anuradh06359394"><strong>Twitter</strong></a> <a target="_blank" href="https://www.instagram.com/blogcode404/"><strong>Instagram</strong></a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Service Workers]]></title><description><![CDATA[Hello folks!! In this article, we'll learn about service workers and their role in creating progressive web apps.
🎯 Introduction

A service worker is a script that runs in the background of a web page, separate from the main page thread.

They are s...]]></description><link>https://anuradha.hashnode.dev/service-workers</link><guid isPermaLink="true">https://anuradha.hashnode.dev/service-workers</guid><category><![CDATA[Service Workers]]></category><category><![CDATA[progressive web apps]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[app development]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Thu, 25 May 2023 03:00:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684983413935/2d52908e-f5a9-4ea8-9458-ba9534a65ea7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello folks!! In this article, we'll learn about service workers and their role in creating progressive web apps.</p>
<h2 id="heading-introduction"><strong>🎯</strong> Introduction</h2>
<blockquote>
<p>A service worker is a script that runs in the background of a web page, separate from the main page thread.</p>
</blockquote>
<p>They are simply a javascript file but not exactly the same as a normal javascript file.</p>
<p>So whenever we create some kind of website we might have a mix of HTML, CSS and javascript files and then we upload those files to the server. When we request them by going to the web address we see them in the browser. Normal javascript file runs on a single thread inside the browser which is tightly coupled with the HTML page and it can access the DOM and manipulate the page content.</p>
<p>Now, when we create a service worker javascript file, it doesn't run on the same thread as our normal javascript file. It runs on a different thread in another part of the browser isolated away from the HTML page. That is why it does not have access to the DOM. So we cannot directly read, change or remove page content.</p>
<blockquote>
<p>Service workers are background process. Their job is to provide an app-like functionality by listening and reacting to the events which occur in the browser.</p>
</blockquote>
<p>Service worker listens to events such as <strong>fetch</strong> HTTP requests made by the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684584226703/2534e12d-c47e-46b1-afd2-f070621766cf.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-service-worker-life-cycle"><strong>🎯</strong> Service Worker Life Cycle</h2>
<p>Service Worker follows the following lifecycle:</p>
<ol>
<li><p><strong>Register</strong>: first register the service worker with the browser. From our normal javascript file (e.g. app.js), we register a service worker basically telling the browser that a certain javascript file (e.g. sw.js) should be registered as a service worker and put onto that separate thread.</p>
</li>
<li><p><strong>Install</strong>: After the registration, the browser downloads and installs the service worker script. We can listen to this lifecycle event inside the `sw.js` file itself. This event is fired only <strong>once</strong> when the service worker is registered. Or the code inside the service worker file has changed since the last time it was installed in the browser.</p>
</li>
<li><p><strong>Active</strong>: When the service worker is installed it becomes active. Once the service worker is active, it can access all the different pages and all the different files <strong>inside its scope.</strong></p>
<p> If we made some changes in the service worker file then it will become active only when all the instances of our app are closed.</p>
</li>
<li><p><strong>Fetch and Cache</strong>: When a fetch event occurs, the service worker intercepts the network request and can respond with cached assets instead of making a network request. This allows the service worker to serve content even when the user is offline. The service worker can also update the cache with fresh content from the network when available.</p>
</li>
<li><p><strong>Update</strong>: When a new version of the service worker is detected by the browser, it is downloaded and installed in the background. The new version enters a "waiting" state while the currently active service worker handles any ongoing events. Once all tabs using the old service worker are closed, the new version takes control during the activation phase, and the cycle continues.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684981025477/7af479d2-2df2-4523-b247-1b31a033b60b.svg" alt class="image--center mx-auto" /></p>
<h2 id="heading-advantages"><strong>🎯</strong> Advantages</h2>
<p>Service workers help to achieve all the things that you would expect in a modern app that runs on a mobile device like:</p>
<ul>
<li><p><strong>Load Content Offline:</strong> you still open and view the app without any internet connection by using cached assets and data.</p>
</li>
<li><p><strong>Use Background Sync:</strong> If a user tries to perform an action while they're offline that normally requires a connection, then it will perform an action in the background when a connection is re-established.</p>
</li>
<li><p><strong>Use Push Notifications:</strong> Our app can notify users on a device</p>
</li>
</ul>
<h2 id="heading-wrap-up"><strong>🎯 Wrap Up!!</strong></h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/"><strong>LinkedIn</strong></a> <a target="_blank" href="https://twitter.com/Anuradh06359394"><strong>Twitter</strong></a> <a target="_blank" href="https://www.instagram.com/blogcode404/"><strong>Instagram</strong></a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Progressive Web Apps]]></title><description><![CDATA[Hello folks!! In this article, we'll learn about the Progressive web app in detail, its advantages and how to create one on your own.
Let's learn how to create simple PWA using HTML, CSS and vanilla JS.
🎯 What is PWA?
PWA stands for "Progressive Web...]]></description><link>https://anuradha.hashnode.dev/progressive-web-apps</link><guid isPermaLink="true">https://anuradha.hashnode.dev/progressive-web-apps</guid><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[progressive web apps]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[frontend]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Tue, 16 May 2023 13:17:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684242839915/ade1bb47-d631-4baa-9744-1459ebfa9cf7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello folks!! In this article, we'll learn about the Progressive web app in detail, its advantages and how to create one on your own.</p>
<p>Let's learn how to create simple PWA using HTML, CSS and vanilla JS.</p>
<h2 id="heading-what-is-pwa"><strong>🎯</strong> What is PWA?</h2>
<p>PWA stands for "Progressive Web App". PWAs are simply alternatives to creating a native mobile app. It is a web application that is designed to provide an app-like experience to users on their mobile devices or desktop browsers, without the need to download and install a native app from an app store.</p>
<p>Using PWAs we can create a mobile app with vanilla javascript that runs inside a browser just like a normal website does but which could also consist of the features of native mobile apps so that when we run that web app on a mobile it could do things that a native app could do as well like:</p>
<ul>
<li><p>Be <strong>installed</strong> onto the home screen of the mobile</p>
</li>
<li><p>Access the application when offline</p>
</li>
<li><p>Get push notifications</p>
</li>
</ul>
<h2 id="heading-advantages-of-pwa"><strong>🎯</strong> Advantages of PWA</h2>
<ul>
<li><p>Can be made using vanilla JS, HTML &amp; CSS</p>
</li>
<li><p>Accessed via a web address and not the app store</p>
</li>
<li><p>Can be installed on the mobile home screen</p>
</li>
<li><p>Runs in the browser but with access to device features</p>
</li>
<li><p>Can be used offline</p>
</li>
<li><p>Can use web push notifications</p>
</li>
</ul>
<h2 id="heading-technical-components-of-pwa"><strong>🎯</strong> Technical components of PWA</h2>
<p>We can simply create a progressive web app using the below components:</p>
<ul>
<li><p>The Web App Manifest</p>
</li>
<li><p>Application Shell</p>
</li>
<li><p>Service Workers</p>
</li>
</ul>
<p>Don't worry if this sounds like bit complicated, we'll look into these components one by one.</p>
<h2 id="heading-basic-setup"><strong>🎯</strong> Basic Setup</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683401054714/62c1f8f5-6a09-473b-b6d9-d5ee733c29b9.png" alt /></p>
<p>We will create a simple web app with three pages <code>Home</code> , <code>About</code> , <code>Contact</code> and later on convert it into PWA.</p>
<p>Let's build a basic setup of our app. We'll start with a simple HTML file.</p>
<p>In <code>index.html</code> file:</p>
<pre><code class="lang-xml"><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>PWA Application<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">"/css/styles.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://unpkg.com/@innovaccer/design-system@2.15.3/css/dist/index.css"</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css?family=Nunito+Sans:300,300i,400,400i,600,600i,700,700i,800,800i,900,900i&amp;display=swap"</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"theme-color"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"#FFE1C4"</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>
    <span class="hljs-attr">class</span>=<span class="hljs-string">"d-flex h-100 align-items-center flex-column justify-content-center"</span>
  &gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">nav</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"p-10"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"links"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/index.html"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"links"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/pages/about.html"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"links"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/pages/contact.html"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">nav</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">"bg-primary p-10"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>My PWA Application<span class="hljs-tag">&lt;/<span class="hljs-name">h2</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>Similarly, create the other two pages <code>About</code> &amp; <code>Contact</code></p>
<h2 id="heading-web-app-manifest"><strong>🎯</strong> Web App Manifest</h2>
<p>This is a single JSON file which is going to provide information about our app to the browser like:</p>
<ul>
<li><p>name of the application</p>
</li>
<li><p>home screen icon for the mobile</p>
</li>
<li><p>colour theme</p>
</li>
<li><p>start URL</p>
</li>
</ul>
<p>By providing the above information, the browser would know how to display our app properly on a mobile when it's <strong>installed</strong> onto it.</p>
<p>By using the Web App Manifest, PWAs can be easily installed on a user's device and provide a more native-like experience, even when accessed through a browser.</p>
<p>On the root of the project, create a file <code>manifest.json</code></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"My PWA App"</span>,
  <span class="hljs-attr">"short_name"</span>: <span class="hljs-string">"PWA"</span>,
  <span class="hljs-attr">"start_url"</span>: <span class="hljs-string">"/index.html"</span>,
  <span class="hljs-attr">"display"</span>: <span class="hljs-string">"standalone"</span>,
  <span class="hljs-attr">"background_color"</span>: <span class="hljs-string">"#FFE9D2"</span>,
  <span class="hljs-attr">"theme_color"</span>: <span class="hljs-string">"#FFE1C4"</span>,
  <span class="hljs-attr">"orientation"</span>: <span class="hljs-string">"portrait-primary"</span>,
  <span class="hljs-attr">"icons"</span>: [
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-72x72.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"72x72"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-96x96.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"96x96"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-128x128.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"128x128"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-144x144.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"144x144"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-152x152.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"152x152"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-192x192.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"192x192"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-384x384.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"384x384"</span>
    },
    {
      <span class="hljs-attr">"src"</span>: <span class="hljs-string">"/img/icons/icon-512x512.png"</span>,
      <span class="hljs-attr">"type"</span>: <span class="hljs-string">"image/png"</span>,
      <span class="hljs-attr">"sizes"</span>: <span class="hljs-string">"512x512"</span>
    }
  ]
}
</code></pre>
<ul>
<li><p><code>name</code>: the name of your app, this is going to be shown when you click on the application on the splash screen while the application loads in the mobile.</p>
</li>
<li><p><code>short_name</code>: the name that displays underneath the icon on the home screen when someone installs your application.</p>
</li>
<li><p><code>start_url</code>: the URL of the page that actually opens up when the user taps on the icon when we install it onto the home screen.</p>
</li>
<li><p><code>display</code>: it specifies the developers' preferred display mode for the website. By selecting "standalone" it's not going to show the other browser things like the address bar at the top.</p>
</li>
<li><p><code>icons</code>: An array of objects and each object represents a different icon. Depending on the device we are installing the app on, it's going to use a different-sized icon.</p>
</li>
</ul>
<p>Don't forget to include this <code>manifest.json</code> file inside your all HTML files like this:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"manifest"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/manifest.json"</span> /&gt;</span>
</code></pre>
<p>Now you can all those properties which you have provided inside the browser in the <strong>Application</strong> Tab:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683828894729/308f6003-57b8-4dab-8532-6bcb753adb25.png" alt class="image--center mx-auto" /></p>
<p>Browser will take all the information and when we install this onto our mobile device it can make sure that our app displays properly.</p>
<p>You can read more about web app manifest [here](<a target="_blank" href="https://web.dev/add-manifest/">https://web.dev/add-manifest/</a>)</p>
<h2 id="heading-application-shell"><strong>🎯</strong> Application Shell</h2>
<p>Now let's move to the next component of PWA i.e. Application Shell.</p>
<p>The app shell is the minimum HTML, CSS, and javascript that is required to power the user interface of PWAs. It represents the <strong>static</strong> parts of the app that remain consistent across different views or pages. This includes components like the header, footer, navigation menu, and other UI elements that are visible on every page.</p>
<p>By caching the App Shell in the service worker, PWAs can load instantly and provide a smooth user experience even in offline or low connectivity scenarios.</p>
<p>The App Shell provides a consistent UI and navigation experience throughout the app, making it feel more like a native application.</p>
<p>There are more important concepts of PWA like service workers etc. which we will cover in the next article.</p>
<h2 id="heading-wrap-up"><strong>🎯</strong> Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
]]></content:encoded></item><item><title><![CDATA[Serverless Functions & FaaS with Vercel]]></title><description><![CDATA[🎯 What are Serverless means?

At first glance, it looks like an application without a server. But it's not.

It basically means you're not responsible for managing and provisioning the servers.

These servers are managed by the cloud provider and yo...]]></description><link>https://anuradha.hashnode.dev/serverless-functions-faas-with-vercel</link><guid isPermaLink="true">https://anuradha.hashnode.dev/serverless-functions-faas-with-vercel</guid><category><![CDATA[Vercel]]></category><category><![CDATA[FaaS]]></category><category><![CDATA[serverless]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Tue, 04 Apr 2023 20:20:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680641150540/876b5838-cb44-4694-931e-9c59e543e2cd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-are-serverless-means"><strong>🎯</strong> What are Serverless means?</h2>
<ul>
<li><p>At first glance, it looks like an application without a server. But it's not.</p>
</li>
<li><p>It basically means you're not responsible for managing and provisioning the servers.</p>
</li>
<li><p>These servers are managed by the cloud provider and you as a developer has to focus more on the development part or writing your business logic.</p>
</li>
</ul>
<h2 id="heading-serverless-function"><strong>🎯</strong> Serverless Function</h2>
<ul>
<li><p>A serverless function refers to a <strong>single-purpose piece of code.</strong></p>
</li>
<li><p>It enables running code on-demand without the need to manage your own infrastructure, provision servers, or upgrade hardware.</p>
</li>
</ul>
<h2 id="heading-function-as-a-service"><strong>🎯</strong> Function as a Service</h2>
<ul>
<li><p>"<strong>Function a</strong>s <strong>a S</strong>ervice" (<strong>FaaS)</strong> is actually a subset of serverless functions.</p>
</li>
<li><p>Serverless functions can fall into any service category where the configuration and management of servers are invisible to the end user.</p>
</li>
<li><p>FaaS, on the other hand, refers exclusively to event-driven computing wherein the code only runs in response to specific events or requests.</p>
</li>
</ul>
<h2 id="heading-how-does-it-work"><strong>🎯</strong> How does it work?</h2>
<p>All the cloud providers have "<strong>Function a</strong>s <strong>a S</strong>ervice" (FaaS). This is essentially a computing platform for serverless where you run your functions. Functions may contain your business logic or code you want to execute on the trigger of any event.</p>
<p>Event here refers to any action performed through your application like the click of a button or submitting a form, etc. which creates an event and then calls your function and runs your code.</p>
<p>Serverless functions are built using these steps:</p>
<ol>
<li><p>create a serverless function</p>
</li>
<li><p>deploy it to a platform</p>
</li>
<li><p>call it through an API from your frontend code (using something like fetch or an Axios)</p>
</li>
</ol>
<h2 id="heading-advantages-of-serverless"><strong>🎯</strong> Advantages of Serverless</h2>
<ul>
<li><p><strong>Pay for execution only</strong>: you only pay for the server resources you use. When your function is running, that's the only time you are paying for that and it's very cost-efficient.</p>
</li>
<li><p><strong>Auto-scalable:</strong> Cloud providers automatically add server capacity when you need it and then take it away when you don’t, you don’t have to worry about maintaining and scaling servers to fit the evolving needs of your website or application.</p>
</li>
<li><p><strong>Invest more time in development:</strong> Since you are not responsible for any of the management and deployment of any underlying infrastructure, you can build your apps faster.</p>
</li>
<li><p><strong>High Availability:</strong> Cloud providers take care of all the fault tolerance and make sure that your app is always up and running.</p>
</li>
</ul>
<h2 id="heading-drawbacks-of-serverless"><strong>🎯</strong> Drawbacks of Serverless</h2>
<ul>
<li><p><strong>Timeouts:</strong> These are basically stateless containers, they run for a little bit of time and are deleted afterwards. So if your execution code does not finish in that time, your app could fail.</p>
</li>
<li><p><strong>Debugging</strong>: It is generally more challenging to debug serverless code.</p>
</li>
<li><p><strong>Not handling Stateful applications</strong>: Serverless is not a good choice when it comes to stateful applications. A stateless application means that every transaction is performed as if it were being done for the very first time. <strong>There is no previously stored information used for the current transaction</strong>.</p>
</li>
</ul>
<p>Now enough of the introduction!! Let's move to the code part.</p>
<h2 id="heading-create-a-serverless-function-on-vercel"><strong>🎯</strong> Create a Serverless Function on Vercel</h2>
<blockquote>
<p>Vercel is a cloud platform for static frontends and serverless functions.</p>
</blockquote>
<h3 id="heading-step-1-install-vercel-cli"><strong>🔍</strong> Step 1: Install Vercel CLI</h3>
<pre><code class="lang-powershell">npm i <span class="hljs-literal">-g</span> vercel@latest
</code></pre>
<p>You should have the latest version of Vercel CLI installed to proceed further.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680633957685/c3ff8069-2250-4b6b-bb4f-b835d26dd27f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-2-create-a-nextjs-project"><strong>🔍</strong> Step 2: Create a Next.js project</h3>
<pre><code class="lang-powershell">npx create<span class="hljs-literal">-next</span><span class="hljs-literal">-app</span>@latest -<span class="hljs-literal">-typescript</span>
</code></pre>
<p>This will create a next.js project for you with a single API Route. This is where we create our Serverless Function.</p>
<h3 id="heading-step-3-create-a-serverless-function"><strong>🔍</strong> Step 3: Create a Serverless Function</h3>
<p>Inside <code>pages/api/handler.ts</code> file write your function:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { NextApiRequest, NextApiResponse } <span class="hljs-keyword">from</span> <span class="hljs-string">"next"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handler</span>(<span class="hljs-params">
  request: NextApiRequest,
  response: NextApiResponse
</span>) </span>{
  response.status(<span class="hljs-number">200</span>).json({
    body: <span class="hljs-string">'This is my Serverless Function'</span>,
    query: request.query,
  });
}
</code></pre>
<p>Use Vercel CLI to start a local development server:</p>
<pre><code class="lang-powershell">vercel dev
</code></pre>
<p>Now navigate to the <code>http://localhost:3000/api/handler</code> to see the response:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680635232269/5e7e9b98-1241-46ac-8fdb-c049715527b9.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-4-deploy-a-serverless-function"><strong>🔍</strong> Step 4: Deploy a Serverless Function</h3>
<p>You can deploy your Serverless Function to Vercel's global <a target="_blank" href="https://vercel.com/docs/concepts/edge-network/overview">Edge Network</a> by running the following command from your terminal:</p>
<pre><code class="lang-powershell">vercel deploy
</code></pre>
<p>The Serverless Function can then be accessed by navigating to the URL provided in the terminal.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680635515600/1bbb3f35-bf2b-480a-b712-13afc4e04a6f.png" alt class="image--center mx-auto" /></p>
<p>Now if you open the URL provided in the terminal, you'll see your serverless function live on production.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680635774061/e6f3478d-d885-4ebe-a9fb-77e8d767fce1.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-5-check-logs"><strong>🔍</strong> Step 5: Check Logs</h3>
<p>You can view all the details of your project on the Vercel web dashboard.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680636402180/19a6f853-9c0a-448b-b7d3-1e28a45a47bd.png" alt class="image--center mx-auto" /></p>
<p>You can now use this as an API endpoint in your frontend application and trigger this function to execute your business logic when any event occurs from your application.</p>
<h2 id="heading-resources"><strong>🎯</strong> Resources</h2>
<ul>
<li><p><a target="_blank" href="https://vercel.com/docs/concepts/functions/serverless-functions/quickstart">Vercel Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://vercel.com/docs/concepts/functions/serverless-functions">Serverless Function Overview</a></p>
</li>
</ul>
<h2 id="heading-wrap-up"><strong>🎯</strong> Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together. <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
]]></content:encoded></item><item><title><![CDATA[Kubernetes - With Mongo & Express App]]></title><description><![CDATA[In this article, we'll see how kubernetes work in practice and will create a demo application using MongoDB and Express.
🎯 Minikube

Open source tool

One node kubernetes cluster that runs in a virtual box.

One node cluster where the master and wor...]]></description><link>https://anuradha.hashnode.dev/kubernetes-with-mongo-express-app</link><guid isPermaLink="true">https://anuradha.hashnode.dev/kubernetes-with-mongo-express-app</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[Express]]></category><category><![CDATA[Devops]]></category><category><![CDATA[containers]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 01 Jan 2023 20:31:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672604969534/370de956-1508-4ad7-ba4c-df2861d27985.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we'll see how kubernetes work in practice and will create a demo application using MongoDB and Express.</p>
<h2 id="heading-minikube"><strong>🎯</strong> Minikube</h2>
<ul>
<li><p>Open source tool</p>
</li>
<li><p>One node kubernetes cluster that runs in a virtual box.</p>
</li>
<li><p>One node cluster where the master and worker processes both run on one node</p>
</li>
<li><p>It has docker container runtime pre-installed.</p>
</li>
<li><p>It runs on your machine using a virtual box or some other hypervisor. So minikube will create a virtual box on your laptop and the node will run inside that virtual box.</p>
</li>
</ul>
<h2 id="heading-kubectl"><strong>🎯</strong> Kubectl</h2>
<ul>
<li><p>It provides a way to interact with the cluster, to create a pod or another K8s component.</p>
</li>
<li><p>kubectl is a command line tool for the K8s cluster.</p>
</li>
</ul>
<h2 id="heading-local-setup"><strong>🎯</strong> Local Setup</h2>
<h4 id="heading-1-install-hypervisor">🧩 1. Install hypervisor</h4>
<p>Minikube needs virtualization or hypervisor so first install it.</p>
<pre><code class="lang-bash">brew install hyperkit
</code></pre>
<h4 id="heading-2-install-minikube">🧩 2. Install Minikube</h4>
<pre><code class="lang-bash">brew install minikube
</code></pre>
<p>minikube has kubectl as a dependency, so the above command will install kubectl as well.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670778811879/kM1dEGYhN.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-3-create-and-start-cluster">🧩 3. Create and start Cluster</h4>
<p>Use the following command to start a K8s cluster</p>
<pre><code class="lang-bash">minikube start --vm-driver=hyperkit
</code></pre>
<p>Minikube needs to be run inside a virtual box so we need to tell Minikube which hypervisor it should use to start the cluster. Therefore in the <strong>start command,</strong> we mention the hyperkit hypervisor.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669574493453/0B_A8-cpo.png" alt="Screenshot 2022-11-28 at 12.11.26 AM.png" /></p>
<h4 id="heading-4-minikube-dashboard">🧩 4. Minikube Dashboard</h4>
<p>Use the following command to open the minikube dashboard UI in the browser</p>
<pre><code class="lang-bash">minikube dashboard
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672602520927/aaddfe78-be0c-466a-8aed-8b1eed1c458a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-yaml-configuration-file"><strong>🎯</strong> YAML Configuration File</h2>
<p>Every configuration file in K8s has 3 parts:</p>
<ul>
<li><p><strong>Metadata:</strong> The first part contains information about the metadata of that component</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672479115976/c1c6c65e-5d07-4949-b90c-1af97ecdd3d5.png" alt class="image--center mx-auto" /></p>
<p>  There is one key called <strong>kind</strong> mentioned in the configuration file which defines what K8s component we are targeting.</p>
</li>
<li><p><strong>Status:</strong> It will be automatically generated and added by the K8s.</p>
</li>
<li><p><strong>Specification:</strong> where we put every kind of configuration that we want to apply for that component. Attributes of "spec" are specific to the <strong>kind</strong> of component that we are creating.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672479272338/289701fa-f33c-434e-8e34-1f0edce70df3.png" alt class="image--center mx-auto" /></p>
<p>  Inside <strong>Specification,</strong> there is another section called <strong>Template.</strong></p>
</li>
</ul>
<p><strong>Template</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672479812282/72c8a191-bc38-4342-b8b2-fdbe653c4dc6.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>It has its own "metadata" and "spec" section.</p>
</li>
<li><p>The configuration mentioned inside the template is applied to a pod</p>
</li>
<li><p>Template specification specifies which image needs to be used, on which port it should run and its name.</p>
</li>
</ul>
<p><strong>The labels &amp; Selectors</strong></p>
<ul>
<li><p>metadata part contains the label and the specification part contains the selectors.</p>
</li>
<li><p>In metadata, we give component labels in key-value pairs.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672492569978/b9cf71a2-18b4-495b-a8ab-530301adde82.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>This label is matched by the selector to create a connection. So this way deployment will know which pods belong to it.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672493064367/54987911-9f09-4473-9125-dd67891591df.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h2 id="heading-demo-project"><strong>🎯</strong> Demo Project</h2>
<p>Now that we have enough understanding of the K8s concept, let's deep dive to create a demo project to get a more clear picture.</p>
<p>We will create a demo express application and connect it with the MongoDB database and will see step by step guide on how each K8s component comes into the picture.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672520017213/ac49556c-5ff9-40f3-9084-31a9ff154a0b.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-step-1-create-a-mongodb-deployment">🔍 Step 1: Create a MongoDB Deployment</h4>
<p>In K8s we do not directly work with the Pods but there is an abstraction layer over a Pod called <strong>Deployment</strong> with which we will directly work.</p>
<p>In <code>mongo-deployment.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-deployment</span>
  <span class="hljs-attr">labels:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">mongodb</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">1</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">mongodb</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">mongodb</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">containers:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb</span>
        <span class="hljs-attr">image:</span> <span class="hljs-string">mongo</span>
        <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">27017</span>
        <span class="hljs-attr">env:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">MONGO_INITDB_ROOT_USERNAME</span>
          <span class="hljs-attr">valueFrom:</span>
            <span class="hljs-attr">secretKeyRef:</span>
              <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-secret</span>
              <span class="hljs-attr">key:</span> <span class="hljs-string">mongo-root-username</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">MONGO_INITDB_ROOT_PASSWORD</span>
          <span class="hljs-attr">valueFrom:</span> 
            <span class="hljs-attr">secretKeyRef:</span>
              <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-secret</span>
              <span class="hljs-attr">key:</span> <span class="hljs-string">mongo-root-password</span>
</code></pre>
<ul>
<li><p>In the <strong>image,</strong> we have specified "mongo", so it will fetch the latest mongo image from the docker hub.</p>
</li>
<li><p>These require 2 env. variables called <code>MONGO_INITDB_ROOT_USERNAME</code> &amp; <code>MONGO_INITDB_ROOT_PASSWORD</code> . To get these values we will create a <strong>Secret</strong> from where we will reference that value.</p>
</li>
<li><p><code>secretKeyRef.name</code> : specifies the name of the secret (which we have defined in Step 2)</p>
</li>
<li><p><code>secretKeyRef.key</code> : specifies the <strong>key</strong> name which we have declared under the <strong>data</strong> section in Step 2.</p>
</li>
<li><p><strong>Please note: Secret</strong> must be created before the <strong>deployment</strong> because this deployment step has dependency over the Secret step.</p>
</li>
<li><p>Create a deployment using the following command:</p>
<pre><code class="lang-bash">  kubectl apply -f mongo-deployment.yaml
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672525537443/2dddd069-c817-4058-895e-9ab17e9dbb3c.png" alt class="image--center mx-auto" /></p>
<p>  Use the following command to get all the K8s components:</p>
<pre><code class="lang-bash">  kubectl get all
</code></pre>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672578911001/63b8444a-9448-43b1-b75e-688d2da0146c.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">kubectl get events
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672581045190/06364294-0883-4b3f-99e3-e5609b5b5830.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-step-2-create-secrets">🔍 Step 2: Create Secrets</h4>
<p>We need credentials (username or password) to connect to the database.</p>
<p>So we're going to create a <strong>Secret</strong> that contains the credentials.</p>
<p>In <code>mongo-secret.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Secret</span>
<span class="hljs-attr">metadata:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-secret</span>
<span class="hljs-attr">type:</span> <span class="hljs-string">Opaque</span>
<span class="hljs-attr">data:</span>
    <span class="hljs-attr">mongo-root-username:</span> <span class="hljs-string">dXNlcm5hbWU=</span>
    <span class="hljs-attr">mongo-root-password:</span> <span class="hljs-string">cGFzc3dvcmQ=</span>
</code></pre>
<ul>
<li><p>Values inside the <strong>data</strong> are not plain text this should be encrypted in some way. Storing the data in a Secret component doesn't automatically make it secure.</p>
</li>
<li><p>We can easily generate the base64 encoded for any plain text using the following command:</p>
<pre><code class="lang-bash">  <span class="hljs-built_in">echo</span> -n <span class="hljs-string">'plain text'</span> | base64  

  // Output: cGxhaW4gdGV4dA==
</code></pre>
</li>
<li><p><strong>Secret</strong> must be created before the <strong>deployment.</strong> So let's first create a Secret component using the following command:</p>
<pre><code class="lang-bash">  kubectl apply -f mongo-secret.yaml
</code></pre>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672524158177/68edb71d-394b-4c60-9e2d-2b4626020a3b.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>To get the list of all secrets created:</p>
<pre><code class="lang-bash">  kubectl get secret
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672524563355/ba6df44a-d940-4790-9a49-cd047df4fadf.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h4 id="heading-step-3-create-an-internal-service-for-mongodb">🔍 Step 3: Create an Internal service for MongoDB</h4>
<p>First, we created a MongoDB pod and to talk to that pod we will need an <strong>internal service,</strong> which means no external request to that pod is allowed. Only components inside the same cluster can talk to it.</p>
<p>In <code>mongo-service.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Service</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-service</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">mongodb</span>
  <span class="hljs-attr">ports:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">protocol:</span> <span class="hljs-string">TCP</span>
      <span class="hljs-attr">port:</span> <span class="hljs-number">27017</span>
      <span class="hljs-attr">targetPort:</span> <span class="hljs-number">27017</span>
</code></pre>
<ul>
<li><p><code>app: mongodb</code> this name should be the same as the label name given in Step 1 to connect to the pod through a label.</p>
</li>
<li><p><code>port</code>: service port</p>
</li>
<li><p><code>targetPort</code>: containerPort of deployment</p>
<pre><code class="lang-bash">  kubectl apply -f mongo-service.yaml
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672583041972/be883da0-ea1c-4f66-94fc-6d68e9c38d42.png" alt class="image--center mx-auto" /></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672583231347/2b574533-6d68-493e-ab14-b40c232cfd31.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h4 id="heading-step-4-create-an-express-deployment">🔍 Step 4: Create an Express deployment</h4>
<p>In <code>express-deployment.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">mongo-express</span>
  <span class="hljs-attr">labels:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">mongo-express</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">1</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">mongo-express</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">mongo-express</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">containers:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">mongo-express</span>
        <span class="hljs-attr">image:</span> <span class="hljs-string">mongo-express</span>
        <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">8081</span>
        <span class="hljs-attr">env:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">ME_CONFIG_MONGODB_ADMINUSERNAME</span>
          <span class="hljs-attr">valueFrom:</span>
            <span class="hljs-attr">secretKeyRef:</span>
              <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-secret</span>
              <span class="hljs-attr">key:</span> <span class="hljs-string">mongo-root-username</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">ME_CONFIG_MONGODB_ADMINPASSWORD</span>
          <span class="hljs-attr">valueFrom:</span> 
            <span class="hljs-attr">secretKeyRef:</span>
              <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-secret</span>
              <span class="hljs-attr">key:</span> <span class="hljs-string">mongo-root-password</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">ME_CONFIG_MONGODB_SERVER</span>
          <span class="hljs-attr">valueFrom:</span> 
            <span class="hljs-attr">configMapKeyRef:</span>
              <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-configmap</span>
              <span class="hljs-attr">key:</span> <span class="hljs-string">database_url</span>
</code></pre>
<ul>
<li><p>In the <strong>image,</strong> we have specified "mongo-express", so it will fetch the latest mongo-express image from the docker hub.</p>
</li>
<li><p>This image will require a <strong>database name</strong> to connect for which we will require a MongoDB address or internal service. We will specify the database URL inside config map in Step 5.</p>
</li>
<li><p>Next, we need credentials for authentication <code>ME_CONFIG_MONGODB_ADMINUSERNAME</code> &amp; <code>ME_CONFIG_MONGODB_ADMINPASSWORD</code> . These are same secrets which we have created in Step 2.</p>
<pre><code class="lang-bash">  kubectl apply -f express-deployment.yaml
</code></pre>
</li>
</ul>
<h4 id="heading-step-5-create-config-map-for-express-app">🔍 Step 5: Create Config Map for Express App</h4>
<p>First, we will need the database URL of MongoDB, so that our express app can connect to the database.</p>
<p>In Config Map, we'll specify all the centralised &amp; external configuration.</p>
<p>So we will create <strong>Config Map</strong> that contains the database URL.</p>
<p>In <code>express-configmap.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">ConfigMap</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">mongodb-configmap</span>
<span class="hljs-attr">data:</span>
  <span class="hljs-attr">database_url:</span> <span class="hljs-string">mongodb-service</span>
</code></pre>
<ul>
<li><p><code>database_url</code> : it is MongoDB internal service name which we have specify in Step 3 above.</p>
</li>
<li><p>ConfigMap must already be in the cluster when referencing it in previous step.</p>
<pre><code class="lang-bash">  kubectl apply -f express-configmap.yaml
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672601354802/151d7131-77a4-4ae5-8eaf-ae14b7ced6f0.png" alt class="image--center mx-auto" /></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672601426029/214420ec-2e79-401a-8c84-0522326a9fb1.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h4 id="heading-step-6-create-an-external-service-for-express-app">🔍 Step 6: Create an External Service for Express App</h4>
<p>We need an external service so that it can be accessed through a browser.</p>
<p>In <code>express-service.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Service</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">mongo-express-service</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">mongo-express</span>
  <span class="hljs-attr">type:</span> <span class="hljs-string">LoadBalancer</span>  
  <span class="hljs-attr">ports:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">protocol:</span> <span class="hljs-string">TCP</span>
      <span class="hljs-attr">port:</span> <span class="hljs-number">8081</span>
      <span class="hljs-attr">targetPort:</span> <span class="hljs-number">8081</span>
      <span class="hljs-attr">nodePort:</span> <span class="hljs-number">30000</span>
</code></pre>
<ul>
<li><p>We have exposed a service port at 8081.</p>
</li>
<li><p>TargetPort is where the container port is listening.</p>
</li>
<li><p><strong>To make it external service:</strong></p>
<ul>
<li><p>add <code>type: LoadBalancer</code></p>
</li>
<li><p>define <code>nodePort</code> where the external IP address is open. This nodePort actually has a range between <strong>30000 - 32767.</strong></p>
<pre><code class="lang-yaml">  <span class="hljs-string">kubectl</span> <span class="hljs-string">apply</span> <span class="hljs-string">-f</span> <span class="hljs-string">express-service.yaml</span>
</code></pre>
<pre><code class="lang-yaml">  <span class="hljs-string">kubectl</span> <span class="hljs-string">get</span> <span class="hljs-string">services</span>
</code></pre>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672601114085/dea49910-82fa-433c-a63f-ae3ed6c9303d.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">  minikube service mongo-express-service
</code></pre>
<ul>
<li>This command will assign public IP address to an external service</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672600979233/8b0cf071-8882-40e0-9cf7-2a819abb08da.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672601053810/1dabab5d-70f5-440a-bdad-487e870c7281.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-kubectl-basic-commands"><strong>🎯</strong> Kubectl Basic Commands</h2>
<p>✏️ <strong>Get Status of K8s Components</strong></p>
<ul>
<li><code>kubectl get nodes</code> : get the status of nodes</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672414194187/68872244-7973-4893-b80f-ff06f4b2dcc5.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p><code>kubectl version</code>: get the latest version</p>
</li>
<li><p><code>kubectl get services</code>: get a list of all services</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672420583244/f4fd01a7-dd4e-426b-ac2c-26369ba2c558.png" alt class="image--center mx-auto" /></p>
<h5 id="heading-debugging-pods">✏️ <strong>Debugging Pods</strong></h5>
</li>
<li><p><code>kubectl logs [POD_NAME]</code>: shows what the application inside the pod logs.</p>
</li>
<li><p><code>kubectl describe pod [POD_NAME]</code>: shows additional information about pods and all the state changes that happen inside the pod.</p>
</li>
<li><p><code>kubectl exec -it [POD_NAME] -- bin/bash</code> : start a shell session for containers running in a K8s cluster. It’s a bit like SSH for Kubernetes.</p>
<h5 id="heading-crud-operations">✏️ <strong>CRUD Operations</strong></h5>
</li>
<li><p><code>kubectl create deployment [DEPLOYMENT_NAME]</code>: to create a deployment</p>
</li>
<li><p><code>kubectl get deployments</code>: to get a list of all deployments</p>
</li>
<li><p><code>kubectl edit deployment [DEPLOYMENT_NAME]</code>: to update the deployment</p>
</li>
<li><p><code>kubectl delete deployment [DEPLOYMENT_NAME]</code>: to delete deployment</p>
<h5 id="heading-resource-metrics">✏️ <strong>Resource Metrics</strong></h5>
</li>
<li><p><code>kubectl top pod</code> : Display resource (CPU/memory) usage of pods</p>
</li>
<li><p><code>kubectl top node</code> : Display resource (CPU/memory) usage of nodes</p>
<h2 id="heading-wrap-up"><strong>🎯</strong> Wrap Up!!</h2>
<p>  That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p>  <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Kubernetes: Main Components Overview]]></title><description><![CDATA[🔍 What is K8s?

Kubernetes, also known as K8s, is an open-source system for automating the deployment, scaling, and management of containerized applications.


Open-source container orchestration tool

Developed by Google

Helps you manage container...]]></description><link>https://anuradha.hashnode.dev/kubernetes</link><guid isPermaLink="true">https://anuradha.hashnode.dev/kubernetes</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[#kubernetes #container ]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Orchestration]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Wed, 28 Dec 2022 16:04:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672243401949/ad1da27c-cd9d-488b-a95d-ea5e0282558b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-k8s">🔍 What is K8s?</h2>
<blockquote>
<p>Kubernetes, also known as K8s, is an open-source system for automating the deployment, scaling, and management of containerized applications.</p>
</blockquote>
<ul>
<li><p>Open-source container orchestration tool</p>
</li>
<li><p>Developed by Google</p>
</li>
<li><p>Helps you manage <strong>containerized applications</strong> in different deployment environments (like physical machines, virtual machines, or cloud env.)</p>
</li>
</ul>
<h2 id="heading-the-need-for-a-container-orchestration-tool">🔍 The need for a container orchestration tool?</h2>
<ul>
<li><p>Trends from monolith to microservices</p>
</li>
<li><p>Increased usage of containers</p>
</li>
<li><p>Demand for a proper way of managing thousands of containers</p>
</li>
</ul>
<p>Containers offer the perfect host for small independent applications. After the increased usage of container technologies now managing those multiple containers across multiple environments using scripts and self-made tools can be complex which leads to the need for some container orchestration tool and then Kubernetes comes into the picture.</p>
<h2 id="heading-what-features-do-k8s-offer">🔍 What features do K8s offer?</h2>
<ul>
<li><p><strong>High Availability</strong> or no downtime: application is always accessible by the user.</p>
</li>
<li><p><strong>Scalability</strong> or high <strong>Performance</strong> (scale out automatically): application loads fast and users have a very high response rate from the application</p>
</li>
<li><p><strong>Disaster recovery</strong>- if infrastructure has some problems like data is lost or the server explodes, a containerized application can be brought back to the latest state after recovery.</p>
</li>
</ul>
<h2 id="heading-k8s-components">🔍 K8s Components</h2>
<p>Let's learn about some of the components of K8s:</p>
<ul>
<li><p>Clusters</p>
</li>
<li><p>Master node &amp; Worker node</p>
</li>
<li><p>Pods</p>
</li>
<li><p>Services</p>
</li>
<li><p>Ingress</p>
</li>
<li><p>Config map</p>
</li>
<li><p>Secrets</p>
</li>
<li><p>Volumes</p>
</li>
<li><p>Deployment &amp; Replica set</p>
</li>
</ul>
<p>Before jumping over these components directly, let's take a case of some javascript application with a simple database and now let's look at how each component of K8s helps you to deploy our application and what is the role of each of the components.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670783436494/_qocpojEN.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-cluster">🎯 Cluster</h3>
<ul>
<li><p>K8s lets you deploy containers on a set of nodes called a <strong>cluster.</strong></p>
</li>
<li><p>A cluster is a set of <strong>master</strong> components that control the system as a whole &amp; a set of <strong>worker</strong> nodes that run containers.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672246065513/acf621b3-577a-4eb0-a4c5-e3521b6cb023.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-pod">🎯 Pod</h3>
<ul>
<li><p>The smallest unit of the K8s cluster</p>
</li>
<li><p>It's an abstraction layer over a container and can contain a group of containers</p>
</li>
<li><p>It creates a running environment or layer on top of the container</p>
</li>
<li><p>The main reason for this abstraction layer is K8s wants to abstract away the container runtime. So we don't have to directly work with container technology.</p>
</li>
<li><p>Each Pod is meant to run <strong>one</strong> application container inside of it. You can also run multiple containers inside one Pod but that's usually the case when there is one main application container and many helpers containers or services that need to be run inside that container.</p>
</li>
<li><p>Each Pod contains a <strong>unique IP address</strong> using which they can communicate with each other. This is an internal IP address.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672151009260/27e35bb1-53d2-419e-b0d9-65a4934e13a2.png" alt class="image--center mx-auto" /></p>
<ul>
<li>One important thing about Pod is that they can die very easily and if that happens new Pod is created in its place and a <strong>new IP address</strong> is assigned to them which may be inconvenient if we are communicating with our database using that IP address because we now have to adjust it every time new Pod restarts. To tackle this problem another component of K8s comes into the picture called <strong>Services.</strong></li>
</ul>
<h3 id="heading-services">🎯 Services</h3>
<ul>
<li><p>It's a static IP address or permanent IP address that can be attached to each Pod.</p>
</li>
<li><p>A service groups a set of pods together &amp; provides a stable endpoint for them.</p>
</li>
<li><p>The lifecycle of pods and services is not connected so even if the pod dies, the service and its IP address will stay the same.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672152070109/0d902e28-c63c-4a11-98e8-08e709137596.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h3 id="heading-ingress">🎯 Ingress</h3>
<ul>
<li><p>Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster.</p>
</li>
<li><p>The role of Ingress is to maintain the DNS routing configurations.</p>
</li>
<li><p>This enables you to access your application through a browser. For this, you need to create an <strong>external service.</strong> External service is a service that opens communication through external sources.</p>
</li>
<li><p>But we don't want our database to be accessible through public request so for that we will create an <strong>internal service.</strong></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672153645414/1646103d-f835-4808-ba68-41a0c9aac359.png" alt class="image--right mx-auto mr-0" /></p>
</li>
</ul>
<h3 id="heading-config-maps">🎯 Config Maps</h3>
<ul>
<li><p>Pods communicate with each other using services. For example, our application will have a database endpoint using which we can communicate with our databases but where should we configure this endpoint??</p>
</li>
<li><p>Config map provides external configuration to your application or some other services that you use and in K8s you just connect it to the Pod so that pod gets the data that configMap contains. So in future, if we change the name of a service or endpoint for that service we just need to update the configMap.</p>
</li>
<li><p>Configuration may also contain the credentials of the database or any other private information which cannot be stored in a plain text format so for that we will use <strong>Secret.</strong></p>
</li>
</ul>
<h3 id="heading-secret">🎯 Secret</h3>
<ul>
<li><p>Just like config maps but used to store secret data.</p>
</li>
<li><p>It's not stored in a plain text format but in a base64 encoded format.</p>
</li>
<li><p>This may contain things like credentials, passwords, certificates etc. which you don't want other people to have access to.</p>
</li>
<li><p>We will connect this secret to the pods so that pods can have access to that information.</p>
</li>
</ul>
<h3 id="heading-volumes">🎯 Volumes</h3>
<ul>
<li><p>We have a database which our application uses and it regenerates some data but if the database pod gets restarted, the data would be lost but we want our data to be persistent for the long term. So to avoid this scenario here comes the role of Volumes.</p>
</li>
<li><p>It attaches physical storage to a hard drive to your pod and that storage could be either on a local machine meaning the same server node where the pod is running or it could be on the remote storage meaning outside of the K8s cluster maybe cloud storage.</p>
</li>
<li><p>This is used to overcome the problem of data loss whenever pods get restarted.</p>
</li>
<li><p>K8s cluster explicitly doesn't manage any data persistence so taking a backup of the data is the responsibility of the user.</p>
</li>
</ul>
<h3 id="heading-deployments-andamp-replica-set">🎯 Deployments &amp; Replica Set</h3>
<p>Till now our application is running perfectly fine and the user can access it through a browser but what happens if my application pods die or crash or we have to restart the pod because we have built a new container image? This will cause a <strong>downtime</strong> where a user cannot reach my application. So that is exactly where the advantage of distributed systems and containers comes into the picture.</p>
<ul>
<li><p>Instead of relying on 1 application pod or 1 database pod, we will replicate everything on multiple servers. So we would have another node where a replica or clone of our application would run which will also be connected to the <strong>same service</strong>.</p>
<blockquote>
<p>Service also acts as a load balancer. It will catch the request and forward it to whichever pod is least busy.</p>
</blockquote>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672246127293/7fcb3aa4-916d-4d21-9c32-2f5ff41eef81.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>To create a replica we'll define a blueprint for <em>My-App</em> pod and specify how many replicas of that pod you would like to run. That blueprint is called <strong>Deployment.</strong></p>
</li>
<li><p>In K8s we will not directly work with pods instead we will create deployments where we can specify how many replicas we actually want. You can also scale up or scale down the number of replicas you want.</p>
</li>
<li><p>In the case of the database pod, we will create its replica also but here is a catch:- We can't replicate a database using a deployment because the database has a <strong>state.</strong> If we clone or replicate the database they would all need to access the same shared data storage and there you would need some kind of mechanism that manages which pods are currently writing to that storage and which pod is currently reading from that storage to avoid data inconsistencies. This is managed by <strong>Stateful Set.</strong></p>
</li>
<li><p><strong>Deployments</strong> for stateLESS Apps.</p>
</li>
<li><p><strong>Stateful Set</strong> for stateFUL Apps or databases.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672246182117/a630f226-1489-4f4b-8cef-09f4b758624a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-wrap-up">🔍 Wrap Up!!</h2>
<p>  That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p>  <a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[useState Hook In React]]></title><description><![CDATA[🎯 What are Hooks?

Hooks are a new feature addition in React version 16.8 which allows you to use React features without having to write a class.
Previously you could use state only within class components but with hooks now it is possible to use st...]]></description><link>https://anuradha.hashnode.dev/usestate-hook-in-react</link><guid isPermaLink="true">https://anuradha.hashnode.dev/usestate-hook-in-react</guid><category><![CDATA[React]]></category><category><![CDATA[ReactHooks]]></category><category><![CDATA[useState]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[useState hook]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 18 Sep 2022 18:08:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1663524106588/BcQkKuyE0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-are-hooks">🎯 What are Hooks?</h2>
<ul>
<li>Hooks are a new feature addition in React version 16.8 which allows you to use React features without having to write a class.</li>
<li>Previously you could use state only within class components but with hooks now it is possible to use state without writing a class. </li>
<li>Hooks don't work inside classes.</li>
</ul>
<h2 id="heading-why-hooks">🎯 Why Hooks?</h2>
<ul>
<li>To work with classes you have to understand how <strong>this</strong> keyword works in javascript. You also need to remember to bind event handlers in class components.</li>
<li>Classes don't minify very well and make hot reloading very unreliable.</li>
<li>Hooks help to reuse stateful component logic without changing the component hierarchy.</li>
<li>Rather than forcing a split based on the lifecycle methods, hooks let you split one component into smaller functions based on what pieces are related.</li>
</ul>
<h2 id="heading-rules-of-hooks">🎯 Rules of Hooks</h2>
<ul>
<li>Only call hooks at the "Top Level" of your react functions</li>
<li>Don't call hooks inside loops, conditions, or nested functions.</li>
<li>Only call hooks from React functions. Call them from within React functional components and not just any regular javascript function.</li>
</ul>
<p>Now let's learn about the very first hook- <strong>useState</strong> hook.</p>
<p>We will try to understand this using a simple example.</p>
<p>In our example, we'll create a simple button that will increment the value of the counter on the <code>onClick</code> event.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663425021872/xMn0LVvpm.gif" alt="useState-class-component.gif" /></p>
<h2 id="heading-manage-state-using-class-component">🎯 Manage State using Class Component</h2>
<p>First, we'll look at how to implement the same using the <strong>class component</strong>.</p>
<ul>
<li>Create a class component</li>
<li>Create a <code>state</code> variable and initialized it to 0.</li>
<li>Create a method that is capable of setting this state value.</li>
</ul>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">Component</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;

class ClassCounter extends Component {

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-built_in">super</span>(props);

    <span class="hljs-built_in">this</span>.state <span class="hljs-operator">=</span> {
      count: <span class="hljs-number">0</span>
    }
  }

  handleIncrement <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({
      count: <span class="hljs-built_in">this</span>.state.count <span class="hljs-operator">+</span> <span class="hljs-number">1</span>
    })
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>button onClick<span class="hljs-operator">=</span>{<span class="hljs-built_in">this</span>.handleIncrement}<span class="hljs-operator">&gt;</span>
           Increment Value
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>{<span class="hljs-built_in">this</span>.state.count}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
    )
  }
}

export default ClassCounter;
</code></pre><h2 id="heading-usestate-hook">🎯 useState Hook</h2>
<ul>
<li><code>useState</code> is a hook that lets you maintain react state to functional components.</li>
<li>Hooks are just functions so we simply call them. </li>
<li>This hook accepts an argument defining the initial value of the state property. </li>
<li>It returns the pair of values. <code>current value</code> of the state property and a <code>method</code> that is capable of updating that state property.</li>
</ul>
<h3 id="heading-manage-state-using-functional-component">📌 Manage State using Functional Component</h3>
<p>Now let's take a look at how to implement the above example using a <strong>functional component</strong>. </p>
<ul>
<li>Create a functional component</li>
<li>We need a <code>state</code> property initialized to 0.</li>
<li>We need a method capable of setting that state property value.</li>
<li>Syntax which we have used below in <code>const [counter, setCounter] = useState(0);</code> is called <strong>Array Destructuring</strong></li>
<li>The variable <code>counter</code> will always contain the current state value and <code>setCounter</code> will accept an argument and set a counter value to that argument. </li>
</ul>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">useState</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;

export const FunctionalCounter <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [counter, setCounter] <span class="hljs-operator">=</span> useState(<span class="hljs-number">0</span>);

  const handleIncrement <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    setCounter(counter <span class="hljs-operator">+</span> <span class="hljs-number">1</span>);
  }

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>button onClick<span class="hljs-operator">=</span>{handleIncrement}<span class="hljs-operator">&gt;</span>
         Increment Value
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>{counter}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
  )
}
</code></pre><p>Notice the usage of <code>useState</code> hook in the above code snippet. </p>
<ul>
<li>A very first time the component renders a state variable is created and initialized with the default value of 0. The default value is never used on re-renders. </li>
<li>When you click on the button the <code>setCounter</code> method is called which will add 1 to the current counter value.</li>
<li><code>setCounter</code> method will cost the component to re-render. </li>
<li>After the re-render counter will contain the updated value. </li>
</ul>
<h3 id="heading-usestate-with-previous-state">📌 useState with previous state</h3>
<p>Now let's take a look at an example where we'll see how to update the state based on the previous state.</p>
<p>Let's say, we want to implement the count value by 5 each time user clicks on the button.</p>
<p>Let's write a code for the same.</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">useState</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;

export const FunctionalCounterWithPreviousState <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [counter, setCounter] <span class="hljs-operator">=</span> useState(<span class="hljs-number">0</span>);

  const handleIncrement <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-keyword">for</span>(let i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> <span class="hljs-number">5</span>; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>){
      setCounter(counter <span class="hljs-operator">+</span> <span class="hljs-number">1</span>);
    }
  }

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>button onClick<span class="hljs-operator">=</span>{handleIncrement}<span class="hljs-operator">&gt;</span>
          Increment Value
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>{counter}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
  )
}
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663425021872/xMn0LVvpm.gif" alt="useState-class-component.gif" /></p>
<p>When we'll run the above code snippet you will notice that it will not work as expected. But Why?? </p>
<p>Here comes the concept of <strong>Batch Rendering.</strong></p>
<h4 id="heading-batch-rendering">✏️ Batch Rendering</h4>
<p>React may batch multiple <code>setState()</code> calls into a single update for performance.</p>
<p>The main idea is that no matter how many setState calls you make inside a React event handler or synchronous lifecycle method, it will be batched into a single update. That is only one single re-render will eventually happen.</p>
<p>This functionality is relevant for both hooks and regular class components, and its purpose is to prevent unnecessary rendering.</p>
<p>As React updates the state <strong>Asynchronously</strong>, you should not rely on their values for calculating the next state.</p>
<hr />
<p>So what other way we can use to achieve our target? Now we'll use the second form of the <code>setCounter</code> function.</p>
<p>Basically, instead of passing in a value of the new state variable, we pass in the function that has access to the old state value.</p>
<p>So now we'll update our code as follows:</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">useState</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;

export const FunctionalCounterWithPreviousState <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [counter, setCounter] <span class="hljs-operator">=</span> useState(<span class="hljs-number">0</span>);

  const handleIncrement <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-keyword">for</span>(let i <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i <span class="hljs-operator">&lt;</span> <span class="hljs-number">5</span>; i<span class="hljs-operator">+</span><span class="hljs-operator">+</span>){

       <span class="hljs-comment">// Update the value based on the previous value</span>
      setCounter(prevCounter <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> prevCounter <span class="hljs-operator">+</span> <span class="hljs-number">1</span>);
    }
  }

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>button onClick<span class="hljs-operator">=</span>{handleIncrement}<span class="hljs-operator">&gt;</span>Increment Value<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>{counter}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
  )
}
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663447712846/yz01f5irj.gif" alt="useState-batch-rendering.gif" /></p>
<p>Now it will work as expected.</p>
<h3 id="heading-usestate-with-objects">📌 useState with Objects</h3>
<p>Now we will use an object as a state variable with the useState hook. 
So instead of storing a variable, we will work with objects this time.</p>
<p>In the below example, we will initialize the state variable with an object with <strong>firstName</strong> &amp; <strong>lastName</strong> as a key. </p>
<p>Let's take a look at the code first.</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">useState</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;

const HooksWithObject <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [name, setName] <span class="hljs-operator">=</span> useState({firstName: <span class="hljs-string">''</span>, lastName: <span class="hljs-string">''</span>});

  <span class="hljs-keyword">return</span>(
    <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>label<span class="hljs-operator">&gt;</span>Enter FirstName: <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>input 
          <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">'text'</span> 
          value<span class="hljs-operator">=</span>{name.firstName} 
          onChange<span class="hljs-operator">=</span>{e <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> setName({firstName: e.target.<span class="hljs-built_in">value</span>})} 
        <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>label<span class="hljs-operator">&gt;</span>Enter LastName: <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>input 
          <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">'text'</span> 
          value<span class="hljs-operator">=</span>{name.lastName} 
          onChange<span class="hljs-operator">=</span>{e <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> setName({lastName: e.target.<span class="hljs-built_in">value</span>})} 
        <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>firstName: {name.firstName}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>lastName: {name.lastName}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>

  )
}

export default HooksWithObject;
</code></pre><p>In the above code snippet, there are input fields that will update the values of <strong>firstName</strong> &amp; <strong>lastName</strong> as a user types in the input fields.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663512468932/ZkILCD-Pp.gif" alt="useState-with-object.gif" /></p>
<p>As you notice above, whenever a user updates the <strong>lastName</strong> input field, the <strong>firstName</strong> input field gets reset to an empty string and removed from the state variable</p>
<ul>
<li><p>This is happening because <strong><code>useState</code> does not automatically merge and update the object. </strong></p>
</li>
<li><p>This is the key difference between the <strong>setState</strong> in Class Component and <strong>useState</strong> in the functional Component. <code>setState</code> will merge the state whereas <code>useState</code> hook setter function will not merge the state. You can use <strong>spread operator</strong> to handle this situation.</p>
</li>
</ul>
<p>So now update our code accordingly.</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">useState</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;

const HooksWithObject <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [name, setName] <span class="hljs-operator">=</span> useState({firstName: <span class="hljs-string">''</span>, lastName: <span class="hljs-string">''</span>});

  <span class="hljs-keyword">return</span>(
    <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>label<span class="hljs-operator">&gt;</span>Enter FirstName: <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>input 
          <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">'text'</span> 
          value<span class="hljs-operator">=</span>{name.firstName} 
          onChange<span class="hljs-operator">=</span>{e <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> setName({...<span class="hljs-built_in">name</span>, firstName: e.target.<span class="hljs-built_in">value</span>})} 
        <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>label<span class="hljs-operator">&gt;</span>Enter LastName: <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>input 
          <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">'text'</span> 
          value<span class="hljs-operator">=</span>{name.lastName} 
          onChange<span class="hljs-operator">=</span>{e <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> setName({...<span class="hljs-built_in">name</span>, lastName: e.target.<span class="hljs-built_in">value</span>})} 
        <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>firstName: {name.firstName}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>lastName: {name.lastName}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>

  )
}

export default HooksWithObject;
</code></pre><p>In the above code snippet, while setting the name variable on <code>onChange</code> event, we'll first copy every property in the name object and then just overwrite the <strong>firstName</strong> field with a different value.</p>
<p>Now when we'll check our result. It will work as expected.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663516780931/eul00Sz44.gif" alt="useState-with-spread-object.gif" /></p>
<h2 id="heading-summary">🎯 Summary</h2>
<ul>
<li>The useState hook allows you to maintain a state inside functional components.</li>
<li>In classes, the state is always an object. With the useState hook, the state doesn't have to be an object. It can be an array, number, boolean or string, etc.</li>
<li>The useState hook returns an array with 2 elements. The first element is the current value of the state and the second element is a state setter function.</li>
<li>State setter function will cause the component to re-render.</li>
<li>In case your new state value depends on the previous state value you can pass a function to the setter function. The setter function will receive the previous state as its argument.</li>
<li>When dealing with objects or arrays, always make sure to spread your state variable and then call the setter function.  </li>
</ul>
<h2 id="heading-wrap-up">🎯 Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[How to create dynamic pages in Gatsby from MDX and YAML?]]></title><description><![CDATA[Gatsby allows you to tie data from many different sources together and present them in a unified way.
In this article, we'll discuss how to set up Node JS and Gatsby to pull the data, transform it into usable nodes, and auto-generate pages based on t...]]></description><link>https://anuradha.hashnode.dev/how-to-create-dynamic-pages-in-gatsby-from-mdx-and-yaml</link><guid isPermaLink="true">https://anuradha.hashnode.dev/how-to-create-dynamic-pages-in-gatsby-from-mdx-and-yaml</guid><category><![CDATA[Gatsby]]></category><category><![CDATA[YAML]]></category><category><![CDATA[markdown]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 06 Mar 2022 16:19:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1646583510085/ihXhi0UAG.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Gatsby allows you to tie data from many different sources together and present them in a unified way.</p>
<p>In this article, we'll discuss how to set up Node JS and Gatsby to pull the data, transform it into usable nodes, and auto-generate pages based on templates. </p>
<h2 id="heading-data-from-yaml-file">🔍 Data from Yaml File</h2>
<p>We can store our data in a YAML file and then it acts as one of our data sources. </p>
<p>We'll store all our <em>data sources</em> inside the <strong>content</strong> folder.</p>
<p>In <code>content/records.yaml</code> file:</p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Gatsby</span>
  <span class="hljs-attr">description:</span> <span class="hljs-string">Static</span> <span class="hljs-string">Site</span> <span class="hljs-string">Generator</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">HTML</span>
  <span class="hljs-attr">description:</span> <span class="hljs-string">Static</span> <span class="hljs-string">Website</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Node</span> <span class="hljs-string">JS</span>
  <span class="hljs-attr">description:</span> <span class="hljs-string">Server</span> <span class="hljs-string">side</span> <span class="hljs-string">rendering</span>
</code></pre>
<h2 id="heading-source-plugin">🔍 Source Plugin</h2>
<ul>
<li>We know gatsby can work with multiple data sources and it can add them all to our graphQL layer, however, to do this for each source that we use we need to install and register a source plugin, and that way gatsby knows how to connect to that data source.</li>
<li>Source plugins are all registered inside the <strong>gatsby config file</strong> inside the plugin array.</li>
<li>plugins also need to be installed into our project using npm, so gatsby can find them as well.</li>
</ul>
<h3 id="heading-gatsby-source-filesystem-plugin">📍gatsby-source-filesystem Plugin</h3>
<ul>
<li>A gatsby source plugin for sourcing data into your gatsby application from your local filesystem.</li>
<li>Install it using <code>npm install gatsby-source-filesystem</code>.</li>
<li>Register them inside the plugins array in the <code>gatsby-config.js</code> file.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">siteMetadata</span>: {
    <span class="hljs-attr">title</span>: <span class="hljs-string">'Learn Gatsby'</span>,
    <span class="hljs-attr">description</span>: <span class="hljs-string">'step-by-step guide to learn gatsby'</span>,
    <span class="hljs-attr">author</span>: <span class="hljs-string">'Anuradha Aggarwal'</span>,
    <span class="hljs-attr">lang</span>: <span class="hljs-string">'en'</span>,
  },
  <span class="hljs-attr">plugins</span>: [
    {
      <span class="hljs-attr">resolve</span>: <span class="hljs-string">`gatsby-source-filesystem`</span>,
      <span class="hljs-attr">options</span>: {
        <span class="hljs-attr">name</span>: <span class="hljs-string">`records`</span>,
        <span class="hljs-attr">path</span>: <span class="hljs-string">`<span class="hljs-subst">${__dirname}</span>/content/`</span>
      }
    },
  ]
}
</code></pre>
<p>In the above code snippet, we'll provide the path of the directory which contains our yaml file. </p>
<ul>
<li>graphQL treats each file as an individual node. Now we can check in <em>graphiQL</em> that it will create a separate node in the graphQL layer.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646426251323/qiwbOS2PF.png" alt="Screenshot from 2022-03-05 02-06-23.png" /></p>
<ul>
<li>We can have multiple instances of the filesystem source plugin.</li>
<li>For every different folder that we have, we need a different instance in the <strong>gatsby-config.js</strong> file.</li>
</ul>
<p>Now let's see how Gatsby transforms this YAML file.</p>
<h2 id="heading-transformer-plugins">🔍 Transformer Plugins</h2>
<p>We want gatsby to know that this file exists and we want you to process it as a YAML file so that we get a JSON object in return we can parse through GraphQL. That's done using the <strong>gatsby-transformer-yaml</strong>  plugin.</p>
<ul>
<li>There are transformer plugins present for almost any type of data.</li>
<li>The transformer plugin takes a data source &amp; transforms it into something easier to use in our components that we can query in our graphql layer. </li>
<li>Firstly, install transformer plugin for yaml file using <code>npm install gatsby-transformer-yaml</code></li>
<li>Now in <code>gatsby-config.js</code> file, register this plugin.<pre><code class="lang-javascript">plugins: [
  <span class="hljs-string">`gatsby-transformer-yaml`</span>,
  {
    <span class="hljs-attr">resolve</span>: <span class="hljs-string">`gatsby-source-filesystem`</span>,
    <span class="hljs-attr">options</span>: {
      <span class="hljs-attr">name</span>: <span class="hljs-string">`records`</span>,
      <span class="hljs-attr">path</span>: <span class="hljs-string">`<span class="hljs-subst">${__dirname}</span>/content/`</span>
    }
  },
]
</code></pre>
</li>
<li>Now in <strong>graphiQL</strong>, we'll have a new type of content, which contains nodes related to our yaml file as well. Now if you run graphQL query you'll get the exact content that we have stored in our yaml file.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646428266917/hc_ttdwLo.png" alt="Screenshot from 2022-03-05 02-40-41.png" /></p>
<p>With the help of this plugin, we have full access to the data and we can use it to display on the front-end.</p>
<p>Once gatsby is able to access the data from the YAML file through GraphQL we can work with the data the same way as we have done in the <a target="_blank" href="https://anuradha.hashnode.dev/gatsby-and-graphql">previous post</a> using graphQL queries.</p>
<p>This is one example to show how gatsby works with the data present in a different format. But what if we have data and we want to transform it into a separate page. 
Most common use case of gatsby is <em>blogging platform.</em></p>
<p>Now let's see how gatsby works with Markdown files.</p>
<h2 id="heading-generate-pages-from-markdown-file">🔍Generate Pages from Markdown File</h2>
<p>We'll follow the following directory structure for the below code:</p>
<pre><code>📦gatsby<span class="hljs-operator">-</span>project
 ┣ 📂content
 ┃ ┣ 📜blog.mdx
 ┣ 📂<span class="hljs-keyword">public</span>
 ┣ 📂src
 ┃ ┣ 📂components
 ┃ ┃ ┣ 📜Header.js
 ┃ ┃ ┗ 📜Layout.js
 ┃ ┣ 📂pages
 ┃ ┃ ┣ 📜about.js
 ┃ ┃ ┗ 📜index.js
 ┃ ┣ 📂styles
 ┃ ┗ 📂templates
 ┃ ┃ ┗ 📜Blog.js
 ┣ 📜gatsby<span class="hljs-operator">-</span>config.js
 ┣ 📜gatsby<span class="hljs-operator">-</span>node.js
 ┗ 📜package.json
</code></pre><h3 id="heading-step-1-create-markdown-file">📍Step 1: Create Markdown file</h3>
<p>In the first step, we'll create a markdown file inside the <strong>content</strong> folder.</p>
<p>In <code>content/blog.mdx</code> file, create your markdown file </p>
<pre><code class="lang-mdx">---
title: My first blog
description: This file is to show how to use markdown in the gatsby site
---

## What is Lorem Ipsum?
Lorem Ipsum is simply a dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Leeriest sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Lauds PageMaker including versions of Lorem Ipsum.

## Why do we use it?
It is a long-established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem Ipsum will uncover many websites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humor and the like)
</code></pre>
<p>As you notice in the above file we have some data inside <strong>triple dashes</strong>. This data is known as <strong>frontmatter</strong></p>
<h4 id="heading-frontmatter">🪄 Frontmatter</h4>
<blockquote>
<p>Frontmatter in markdown file represents metadata or extra information about that particular file. It is denoted by the triple dashes at the start and end of the block.</p>
</blockquote>
<h3 id="heading-step-2-register-markdown-content-using-source-plugin">📍Step 2: Register markdown content using source plugin</h3>
<p>Now before we'll dynamically pump this data inside our graphQL layer, we need to inform gatsby that these markdown files are present here which will act as one of our data sources. So to do this we will register them inside the <strong>gatsby-config.js</strong> file using the <strong>source plugin</strong> as we have done before for yaml files.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">plugins</span>: [
    {
      <span class="hljs-attr">resolve</span>: <span class="hljs-string">`gatsby-source-filesystem`</span>,
      <span class="hljs-attr">options</span>: {
        <span class="hljs-attr">name</span>: <span class="hljs-string">`blogs`</span>,
        <span class="hljs-attr">path</span>: <span class="hljs-string">`<span class="hljs-subst">${__dirname}</span>/content/`</span>
      }
    }
  ]
}
</code></pre>
<h3 id="heading-step-3-use-transformer-plugin-for-markdown">📍Step 3: Use Transformer plugin for Markdown</h3>
<p>Transformer plugins in gatsby take a data source and transform it into something easier to use in our components that we can query in our graphQL layer.</p>
<p>For the markdown file we'll use the <a target="_blank" href="https://www.gatsbyjs.com/plugins/gatsby-plugin-mdx/">gatsby-plugin-mdx</a> plugin:</p>
<ul>
<li>First, install it using <code>npm install gatsby-plugin-mdx @mdx-js/mdx@v1 @mdx-js/react@v1</code></li>
<li>Register it inside <code>gatsby-config.js</code> file, in <em>plugin</em> array.<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
   <span class="hljs-attr">plugins</span>: [
      <span class="hljs-string">`gatsby-plugin-mdx`</span>
   ]
}
</code></pre>
</li>
</ul>
<p>By default, only files with the <code>.mdx</code> file extension are treated as MDX when using the gatsby-source-filesystem. To use <code>.md</code> or other file extensions, you can define an array of file extensions in the gatsby-plugin-mdx section of your gatsby-config.js.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// gatsby-config.js</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">plugins</span>: [
    {
      <span class="hljs-attr">resolve</span>: <span class="hljs-string">`gatsby-plugin-mdx`</span>,
      <span class="hljs-attr">options</span>: {
        <span class="hljs-attr">extensions</span>: [<span class="hljs-string">`.mdx`</span>, <span class="hljs-string">`.md`</span>],
        <span class="hljs-attr">defaultLayouts</span>: {
          <span class="hljs-attr">default</span>: <span class="hljs-built_in">require</span>.resolve(<span class="hljs-string">"./src/templates/Blog.js"</span>),
        },
      },
    },
  ],
}
</code></pre>
<p>Now when we check on <em>graphiQL</em>, it will show our markdown file content embed into the graphQL layer.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646508342902/hyNG7f-vs.png" alt="Screenshot from 2022-03-06 00-54-16.png" /></p>
<p>As shown in the above image, this plugin comes with the additional feature which gives you the ability to query out <strong>tableOfContent</strong> or <strong>frontmatter</strong> for each markdown file which you can further use in your site.</p>
<h3 id="heading-step-4-create-a-template-for-markdown">📍Step 4: Create a template for Markdown</h3>
<p>Inside the <code>src</code> folder, create a new folder called <strong>templates</strong>, this will store the template required to display the content of our markdown file.</p>
<p>In <code>src/templates/Blog.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { MDXRenderer } <span class="hljs-keyword">from</span> <span class="hljs-string">"gatsby-plugin-mdx"</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> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">"../components/Layout"</span>;

<span class="hljs-keyword">const</span> Blog = <span class="hljs-function">(<span class="hljs-params">{ pageContext }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { blogDescription, blogTitle, body } = pageContext;
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Layout</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{blogTitle}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{blogDescription}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">MDXRenderer</span>&gt;</span>{body}<span class="hljs-tag">&lt;/<span class="hljs-name">MDXRenderer</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Layout</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> Blog;
</code></pre>
<p><strong>pageContext</strong> prop has its special meaning. It gives you access to all the required information of your markdown file.</p>
<h4 id="heading-pagecontext">🪄 pageContext</h4>
<ul>
<li>Using the pageContext props in the template component can come with its performance advantages, of getting in all the data you need at build time; from the <strong>createPages</strong> API. </li>
<li>This removes the need to have a GraphQL query in the template component.</li>
</ul>
<h4 id="heading-mdxrenderer">🪄 MDXRenderer</h4>
<ul>
<li>MDXRenderer is a React component that takes compiled MDX content and renders it. You will need to use this if your MDX content is coming from a GraphQL page query or StaticQuery.</li>
</ul>
<h3 id="heading-step-5-use-gatsby-createpage-api">📍Step 5: Use gatsby createPage API</h3>
<p>We want gatsby to automatically generate pages for each markdown file via <strong>NodeJS</strong>.</p>
<p>To do this we'll use the file called <strong>gatsby-node.js</strong>.</p>
<ul>
<li><strong>gatsby-node.js</strong> file will run at the build time in a node environment so we can run certain functions inside this file to do things like fetch data &amp; then generate pages with that data based on a template file that we have created earlier.</li>
</ul>
<p>To create a page dynamically we'll use the gatsby <a target="_blank" href="https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#createPages">createPage</a> API.</p>
<h4 id="heading-createpage-api">🪄 createPage API</h4>
<blockquote>
<p>Create pages dynamically. This extension point is called only after the initial sourcing and transformation of nodes plus creation of the GraphQL schema are complete so you can query your data in order to create pages.</p>
</blockquote>
<p>In <code>gatsby-node.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">exports</span>.createPages = <span class="hljs-keyword">async</span> ({ actions, graphql, reporter }) =&gt; {
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> graphql(<span class="hljs-string">`
    query {
      allMdx {
        nodes {
          body
          slug
          frontmatter {
            title
            description
          }
        }
      }
    }
  `</span>);

  <span class="hljs-keyword">if</span> (result.errors) {
    reporter.panic(<span class="hljs-string">"failed to create posts "</span>, result.errors);
  }

  <span class="hljs-keyword">const</span> pages = result.data.allMdx.nodes;

  <span class="hljs-comment">// The context object **is** supplied to MDX templates through the pageContext prop.</span>

  pages.forEach(<span class="hljs-function">(<span class="hljs-params">page</span>) =&gt;</span> {
    actions.createPage({
      <span class="hljs-attr">path</span>: page.slug,
      <span class="hljs-attr">component</span>: <span class="hljs-built_in">require</span>.resolve(<span class="hljs-string">"./src/templates/Blog.js"</span>),
      <span class="hljs-attr">context</span>: {
        <span class="hljs-attr">pathSlug</span>: page.slug,
        <span class="hljs-attr">body</span>: page.body,
        <span class="hljs-attr">blogTitle</span>: page.frontmatter.title,
        <span class="hljs-attr">blogDescription</span>: page.frontmatter.description
      },
    });
  });
};
</code></pre>
<p> In the above code snippet, first we'll make an graphQL query and use the gatsby <strong>createPage</strong> API to create new page. Inside this we can define:</p>
<ul>
<li><strong>component</strong>:  It refers to the template you want to use for your markdown file.</li>
<li><strong>context</strong>: this object contains all the data you want to pass to the template as a <em>pageContext</em> prop.</li>
</ul>
<p>Now if you navigate to <code>http://localhost:8000/blog</code> it will show your newly created page from markdown:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646577400602/Ifce4GHmh.png" alt="Screenshot from 2022-03-06 20-05-38.png" /></p>
<p>Finally we have created our first dynamic page 🎉🎉. But there are lot more we can do with the markdown files. Let's see more cool features of MDX.</p>
<h3 id="heading-more-about-mdx">📍More about MDX</h3>
<h4 id="heading-what-is-mdx">🪄 What is MDX?</h4>
<p>According to Gatsby's Official documentation:</p>
<blockquote>
<p>MDX is a markdown for the component era. It lets you write JSX embedded inside markdown. It’s a great combination because it allows you to use markdown’s often terse syntax (such as # heading) for the little things and JSX for more advanced components.</p>
</blockquote>
<ul>
<li>MDX allows you to use React components alongside Markdown. </li>
<li>You can also import and reuse your own React components and even other MDX documents.</li>
</ul>
<p>In your markdown file: </p>
<pre><code class="lang-mdx">--
title: Example to show how to use React Components inside Markdown
---
import { CustomHeading } from "./components/Headings";

## You can import your own components.
&lt;CustomHeading&gt;This will show my custom heading component&lt;/CustomHeading&gt;
</code></pre>
<p>To avoid having to import the same component inside of every MDX document, you can add components to an <strong>MDXProvider</strong> to make them globally available in MDX pages. This pattern is sometimes referred to as <em>shortcodes</em>.</p>
<h4 id="heading-mdxprovider">🪄 MDXProvider</h4>
<ul>
<li>MDXProvider is a React component that allows you to replace the rendering of tags in MDX content. </li>
<li>You can also expose any custom component to every mdx file using MDXProvider</li>
</ul>
<p>To use MDXProvider just make changes in your <code>src/components/Layout.js</code> file:</p>
<pre><code class="lang-javascript"><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> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'./Header'</span>;
<span class="hljs-keyword">import</span> { MDXProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">"@mdx-js/react"</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Layout</span>(<span class="hljs-params">{ children }</span>) </span>{

  <span class="hljs-keyword">const</span> CustomHeading = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> "<span class="hljs-attr">green</span>" }} {<span class="hljs-attr">...props</span>} /&gt;</span></span>

  <span class="hljs-keyword">const</span> components = {
    <span class="hljs-attr">h2</span>: CustomHeading,
  }

  <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">"layout"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"content"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{description}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">hr</span> /&gt;</span>
        {/* content for each page */}
        <span class="hljs-tag">&lt;<span class="hljs-name">MDXProvider</span> <span class="hljs-attr">components</span>=<span class="hljs-string">{components}</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">MDXProvider</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>
  )
}
</code></pre>
<p>Using this, now all the H2 heading inside the mdx file will be updated with our custom heading component.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646579726417/ldJhvqFoz.png" alt="Screenshot from 2022-03-06 20-44-12.png" /></p>
<h2 id="heading-other-useful-resources">🔍 Other Useful Resources</h2>
<ul>
<li><a target="_blank" href="https://www.gatsbyjs.com/plugins/gatsby-plugin-mdx/#mdxprovider">MDXProvider</a></li>
<li><a target="_blank" href="https://www.gatsbyjs.com/docs/creating-and-modifying-pages/">Other ways to create dynamic Pages</a></li>
<li><a target="_blank" href="https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/">Gatsby Node APIs</a></li>
</ul>
<h2 id="heading-wrap-up">🔍 Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Gatsby and GraphQL]]></title><description><![CDATA[Gatsby is a modern take on static site generator which is built on React and uses GraphQL to extract information from data sources. 
In the previous article, we have learned the basics of Gatsby, let's now learn about the relation of Gatsby and Graph...]]></description><link>https://anuradha.hashnode.dev/gatsby-and-graphql</link><guid isPermaLink="true">https://anuradha.hashnode.dev/gatsby-and-graphql</guid><category><![CDATA[Gatsby]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sat, 29 Jan 2022 15:31:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1643470016993/1XG5IZFpZ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Gatsby is a modern take on static site generator which is built on React and uses GraphQL to extract information from data sources. </p>
<p>In the previous <a target="_blank" href="https://anuradha.hashnode.dev/introduction-to-gatsby-part-1">article</a>, we have learned the basics of Gatsby, let's now learn about the relation of Gatsby and GraphQL. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643466115539/MlqP9RweU.png" alt="undraw_gatsbyjs_st4g.png" /></p>
<h2 id="heading-what-is-graphql">🔍 What is GraphQL?</h2>
<ul>
<li>A query language used to query data</li>
<li>Alternative to using a REST APIs</li>
<li>It is one of the ways that you can import data into your Gatsby components. </li>
<li>In GraphQL queries, we do not only specify what we want, but we also specify how we want it structured in return.</li>
</ul>
<p>If you want to learn more about GraphQL, visit <a target="_blank" href="https://graphql.org/">here</a></p>
<h2 id="heading-why-does-gatsby-use-graphql">🔍 Why does Gatsby use GraphQL?</h2>
<p>One of the main features of Gatsby is we can use different data sources for our website e.g. (WordPress, Shopify, Firebase, file System) and Gatsby provides the mechanism using which we can query it and access it the same way from our website using GraphQL queries. </p>
<p>Gatsby basically mesh together all the data sources into a unified GraphQL layer which is also known as <strong>Content Mesh.</strong></p>
<h2 id="heading-graphiql">🔍 GraphiQL</h2>
<p>There is a tool provided by Gatsby that makes GraphQL much easier to understand and work with. If you run <code>gatsby develop</code>, you may have noticed that there are actually two URLs to the local server once the process is complete. </p>
<ul>
<li><code>http://localhost:8000/</code>:- It goes to the live site.</li>
<li><code>http://localhost:8000/___graphql</code>:- It goes to the GraphiQL, an in-browser IDE, to explore your site's data and schema.</li>
</ul>
<p>On this GraphiQL interface we can do the following:</p>
<ul>
<li>You can explore your entire GraphQL setup on your local server.</li>
<li>We can craft custom requests and can directly see their results on the right-hand side.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643463207079/aswdJxzQY.png" alt="Screenshot from 2022-01-29 19-02-39.png" /></p>
<ul>
<li>GraphQL will return JSON objects which later you can parse like any other object in Javascript.</li>
<li>Use <strong>Code Explorer</strong> to know how to use these queries inside your code.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643463359443/r2cD1fVXK.png" alt="Screenshot from 2022-01-29 19-05-34.png" /></p>
<ul>
<li><strong>Code Explorer</strong> provides an option to see how to use different types of queries in your code.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643464950759/q9QqZ_9oc.png" alt="Screenshot from 2022-01-29 19-08-46.png" /></p>
<h2 id="heading-types-of-graphql-queries">🔍 Types of GraphQL Queries</h2>
<p>There are two different types of GraphQL queries which are used in two different circumstances. </p>
<ul>
<li>Page Query</li>
<li>Static Query</li>
</ul>
<h3 id="heading-page-query">✏️ Page Query</h3>
<ul>
<li>A page query sits separately from the main export component. Gatsby is going to find this query and it will return the <strong>data</strong> property inside our component as a prop.</li>
<li>We can use <strong>query variables</strong>, which means we can make its query <em>self-dynamic</em> through passing variables to it.</li>
<li>It only works for pages. We cannot use page queries inside a component. </li>
</ul>
<h3 id="heading-static-query">✏️ Static Query</h3>
<ul>
<li>It sits inside the component itself.</li>
<li>It cannot receive a variable as the name <em>static</em> suggests.</li>
<li><strong>useStaticQuery</strong> is a React hook available to use static query as a separate entity inside our components.</li>
</ul>
<p>Now let's write some code to understand it better!!</p>
<h2 id="heading-write-graphql-query">🔍 Write GraphQL Query</h2>
<p>Now to see how graphQL queries work, let's add some data.</p>
<h3 id="heading-add-site-metadata">✏️ Add Site Metadata</h3>
<p>In the <code>gatsby-config.js</code> file, we'll store our site Metadata. </p>
<pre><code>module.exports <span class="hljs-operator">=</span> {
  siteMetadata: {
    title: <span class="hljs-string">'Learn Gatsby'</span>,
    description: <span class="hljs-string">'step-by-step guide to learn gatsby'</span>,
    author: <span class="hljs-string">'Anuradha Aggarwal'</span>,
    lang: <span class="hljs-string">'en'</span>,
  },
}
</code></pre><p>We'll look at how to use this metadata via graphQL query in the later part.</p>
<p>From the previous post, we have the <code>Layout.js</code> file in the <code>src/components</code> folder.</p>
<pre><code class="lang-javascript"><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> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'./Header'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Layout</span>(<span class="hljs-params">{ children }</span>) </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">"layout"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"content"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to our Gatsby Site :)<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Gatsby is known as static site generator !!!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">hr</span> /&gt;</span>
        {/* content for each page */}
        {children}
      <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>  )
}
</code></pre>
<p>And <code>about.js</code> in the <code>src/pages</code> folder.</p>
<pre><code class="lang-javascript"><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> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Layout'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">About</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">Layout</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">h3</span>&gt;</span>About page<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>description here<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">Layout</span>&gt;</span></span>
  )
}
</code></pre>
<p>Now it's time to write some queries.</p>
<h3 id="heading-write-page-query">✏️ Write Page Query</h3>
<p>As we know <strong>Page Query</strong> only works for pages, let's write some inside our <code>about.js</code> file.</p>
<p><strong>Step 1:  Import GraphQL</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { graphql } <span class="hljs-keyword">from</span> <span class="hljs-string">"gatsby"</span>;
</code></pre>
<p><strong>Step 2: Query SiteMetadata</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> query = graphql<span class="hljs-string">`
  {
    site {
      siteMetadata {
        description
        title
      }
    }
  }
`</span>
</code></pre>
<p>Gatsby is going to find this query and it will return the <strong>data</strong> property inside our component as a prop.</p>
<p><strong>Step 3: Use this query data inside your component</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">About</span>(<span class="hljs-params">{ data }</span>) </span>{
  <span class="hljs-keyword">const</span> { title, description } = data.site.siteMetadata;
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</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">p</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{description}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">Layout</span>&gt;</span></span>
  )
}
</code></pre>
<p>Now at the end, our <code>about.js</code> file will look like this:</p>
<pre><code class="lang-javascript"><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> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Layout'</span>;
<span class="hljs-keyword">import</span> { graphql } <span class="hljs-keyword">from</span> <span class="hljs-string">"gatsby"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">About</span>(<span class="hljs-params">{ data }</span>) </span>{
  <span class="hljs-keyword">const</span> { title, description } = data.site.siteMetadata;
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</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">p</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{description}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">Layout</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> query = graphql<span class="hljs-string">`
  {
    site {
      siteMetadata {
        description
        title
      }
    }
  }
`</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643460357919/sVQcSWTAF.png" alt="Screenshot from 2022-01-29 18-15-35.png" /></p>
<h3 id="heading-write-static-query">✏️ Write Static Query</h3>
<p>Now let's see how to use Static Query.</p>
<p>In <code>Layout.js</code> file:</p>
<p><strong>Step 1:  Import GraphQL &amp; useStaticQuery hook</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { graphql, useStaticQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">'gatsby'</span>;
</code></pre>
<p><strong>Step 2: Query SiteMetadata</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> data = useStaticQuery(graphql<span class="hljs-string">`
    query SiteInfos {
      site {
        siteMetadata {
          description
          title
        }
      }
    }
  `</span>)
</code></pre>
<p><strong>Step 3: Use data in your component</strong></p>
<p>In the end, the <code>Layout.js</code> file will look like this:</p>
<pre><code class="lang-javascript"><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> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'./Header'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Layout</span>(<span class="hljs-params">{ children }</span>) </span>{

  <span class="hljs-keyword">const</span> data = useStaticQuery(graphql<span class="hljs-string">`
    query SiteInfos {
      site {
        siteMetadata {
          description
          title
        }
      }
    }
  `</span>)

  <span class="hljs-keyword">const</span> { title, description } = data.site.siteMetadata

  <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">"layout"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"content"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{description}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">hr</span> /&gt;</span>
        {/* content for each page */}
        {children}
      <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>
  )
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643461015771/Jsk4vc8uA.png" alt="Screenshot from 2022-01-29 18-26-34.png" /></p>
<p>As you see GraphQL is almost the same in both cases, it differs in how to use it inside or outside the components which varies on your use case.</p>
<h2 id="heading-wrap-up">🔍 Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Gatsby: Part - 1]]></title><description><![CDATA[Gatsby, a static site framework using React and GraphQL. It enables you to build fast, accessible & advanced static websites that are easy to maintain.
Static site generator:- A tool that takes code & content and creates static documents to be hosted...]]></description><link>https://anuradha.hashnode.dev/introduction-to-gatsby-part-1</link><guid isPermaLink="true">https://anuradha.hashnode.dev/introduction-to-gatsby-part-1</guid><category><![CDATA[Gatsby]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[GraphQL]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sat, 22 Jan 2022 19:25:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1642877374622/D46KpYnpI.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Gatsby, a static site framework using <strong>React</strong> and <strong>GraphQL</strong>. It enables you to build fast, accessible &amp; advanced static websites that are easy to maintain.</p>
<p><code>Static site generator:-</code> A tool that takes code &amp; content and creates static documents to be hosted and served from the web.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642878755514/NNtncck6t.png" alt="image.png" /></p>
<h3 id="heading-content-mesh">🎯 Content Mesh</h3>
<ul>
<li>Gatsby uses many different data sources for your website e.g. (WordPress, Shopify, Firebase, file System).</li>
<li>Gatsby combines all data sources into a unified GraphQL layer by using a source plugin, which means no matter where your data is loaded from, we can query it and access it the same way from our website using GraphQL queries.</li>
<li>This ability of Gatsby is known as <strong>Content Mesh</strong>: Different data sources can mesh together into a single GraphQL layer.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642878681754/d9kISFmRT.png" alt="image.png" /></p>
<h3 id="heading-gatsby-cli">🎯 Gatsby CLI</h3>
<p><code>gatsby new &lt;site-name&gt;</code>:- lets you create a new gatsby site. </p>
<p><code>gatsby develop</code>:- is one of the scripts available in Gatsby CLI and it does two things:-</p>
<ul>
<li>It runs the build process to generate the static site and then puts that static site into a new folder called <strong>public</strong>. It spins up a local dev server &amp; connects you to that public folder.</li>
<li>Looks for any changes in the files and automatically re-builds the development bundle. You can look at the changes directly to the browser immediately.</li>
</ul>
<p>One of the cool features of gatsby is you can access your dev environment on other devices on the same network using the command <code>gatsby develop -H 0.0.0.0</code>. It provides you the IP address which you can visit on your other devices. This will be very helpful for mobile testing and testing for different screens. </p>
<p>Sometimes you need to make changes in the build process or some config changes in that case you need to stop the development server. </p>
<p><code>gatsby clean</code>:- Used to delete the public folder and cache anytime. It clears what was generated during the build process. It doesn't delete any of your changes, it only wipes off the stuff that was generated to preview in the browser.</p>
<p><code>gatsby build</code>:- compile your application and make it ready for deployment.</p>
<p>You can explore more gatsby-cli commands <a target="_blank" href="https://www.gatsbyjs.com/docs/reference/gatsby-cli/">here</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642879003781/v3JF48D-d.png" alt="image.png" /></p>
<h3 id="heading-initial-setup">🎯 Initial Setup</h3>
<ul>
<li>Install Node JS</li>
<li>Install Git</li>
<li>Install gatsby-cli using the command <code>npm install -g gatsby-cli</code></li>
</ul>
<p>You can use <a target="_blank" href="https://www.gatsbyjs.com/starters/"><strong>Gatsby Starter Library</strong></a>, this is a pre-configured package of a Gatsby setup that has either a very basic site or a fully built out site that you can configure to fit your needs. </p>
<p>For now, we'll use the <code>gatsby-starter-hello-world</code> starter package and install it using:</p>
<pre><code>npx gatsby <span class="hljs-keyword">new</span> gatsby<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>hello<span class="hljs-operator">-</span>world https:<span class="hljs-comment">//github.com/gatsbyjs/gatsby-starter-hello-world</span>
</code></pre><p> Run the development server using <code>gatsby develop</code>.</p>
<h3 id="heading-folder-structure">🎯 Folder Structure</h3>
<p>This is what our folder structure looks like at the end of the project:</p>
<pre><code>📦gatsby<span class="hljs-operator">-</span>project
 ┣ 📂.cache
 ┣ 📂node_modules
 ┣ 📂<span class="hljs-keyword">public</span>
 ┣ 📂src
 ┃ ┣ 📂components
 ┃ ┃ ┣ 📜Layout.js
 ┃ ┣ 📂images
 ┃ ┣ 📂pages
 ┃ ┃ ┣ 📜<span class="hljs-number">404</span>.js
 ┃ ┃ ┣ 📜about.js
 ┃ ┃ ┗ 📜index.js
 ┃ ┣ 📂styles
 ┃ ┗ 📂templates
 ┣ 📂content
 ┃ ┣ 📜about.md
 ┣ 📂static
 ┣ 📜gatsby<span class="hljs-operator">-</span>browser.js
 ┣ 📜gatsby<span class="hljs-operator">-</span>config.js
 ┣ 📜gatsby<span class="hljs-operator">-</span>node.js
 ┣ 📜gatsby<span class="hljs-operator">-</span>ssr.js
 ┣ 📜package<span class="hljs-operator">-</span>lock.json
 ┗ 📜package.json
</code></pre><p>The above diagram represents the folder structure of the simple gatsby project. Let's go through each one of them.</p>
<p><code>package.json</code>:- This is the core file of the entire build process. In this file, you can see all the dependencies that are added to your project and scripts.</p>
<p><code>public</code> folder:- When we run gatsby by using the <code>gatsby develop</code> command, it automatically generates the <strong>public</strong> folder which contains all of the stuff that is being served to the browser and when we deploy our application, this will be the folder that you'll deploy as well after we've run the <code>gatsby build</code> command, As all of the build files will reside in this folder.</p>
<h4 id="heading-gatsbyjs-files">📌 Gatsby.js files</h4>
<p><code>gatsby-ssr.js</code>:- SSR stands for Server-Side-Rendering. SSR is where the server renders a web page, then sends it to the browser, instead of letting the browser render the web page. This file will let you alter the content of static HTML files while they are being rendered by the server.</p>
<p><code>gatsby-node.js</code>:- File that we run in build time in a node environment. You can use it to dynamically create pages, add Graphql Nodes, or respond to events during the build lifecycle.</p>
<p><code>gatsby-config.js</code>:- This file basically exports an object where we can add plug-in information or site metadata.</p>
<p><code>gatsby-browser.js</code>:- file where you can respond to events within the browser and can wrap your site in additional components. Inside this file, you can specify any global CSS or fonts you need to import and made them available everywhere in your project.</p>
<h4 id="heading-pages-andamp-routes">📌 Pages &amp; Routes</h4>
<p><code>src/pages</code> folder:</p>
<ul>
<li>Whenever you create a new file of React component inside the <strong>src/pages folder</strong>, gatsby looks at the file name and it creates a route to match that file name.</li>
<li>We can make sub-directories by making a folder inside the src/pages folder.</li>
<li>Whenever we create <strong>index.js</strong> file inside any folder, then gatsby creates a base route for that directory.</li>
<li>To create a custom 404 page just create a component in your site directory at <strong>src/pages/404.js</strong>.</li>
<li>The custom 404 page is only visible when we deploy our application and not in developer's mode.</li>
</ul>
<p><code>src/components</code> folder:</p>
<ul>
<li>All the components you create to pull into pages or templates or use anywhere else, go under the component folder.</li>
</ul>
<h4 id="heading-static-assets">📌 Static Assets</h4>
<p><code>static</code> folder:</p>
<ul>
<li>Anything you want to be made available as a static asset to the browser can go inside the <strong>static</strong> folder.</li>
<li>Gatsby copied all the static assets to the public folder so that it is accessible by the browser.</li>
<li><strong>Disadvantages</strong>: There are some disadvantages to using static assets: Files that are saved as static assets are taken out from the whole gatsby processing workflow. So they are not processed, minimized, or optimized for the web in any way.</li>
</ul>
<h4 id="heading-add-styles">📌 Add Styles</h4>
<p><code>src/styles</code> folder: </p>
<ul>
<li>We can have a global style common to all the components.</li>
<li><strong>CSS Modules</strong>: Defines a way to scope styles to specific components or pages. So we can create a module, apply it to a specific react component, and as a result, that module will be scoped to that particular component.</li>
</ul>
<h4 id="heading-dynamic-pages">📌 Dynamic Pages</h4>
<p><code>src/templates</code> folder:</p>
<ul>
<li>We can also use Gatsby to automatically generate pages for us. The templates for that pages will go under the <code>src/templates</code> folder.</li>
</ul>
<h4 id="heading-data-sources">📌 Data Sources</h4>
<p><code>content</code> folder:</p>
<ul>
<li>There's also a convention where if you create external content, like markdown files that will turn into pages through a template, you place them in a <strong>content</strong> folder that sits on the root.</li>
<li>It does not sit inside the <em>src</em> folder because it's not part of the source code, it's a <strong>data source.</strong> </li>
</ul>
<h3 id="heading-create-static-pages">🎯 Create Static Pages</h3>
<p>Now let's create some static pages.</p>
<p>To create a layout of our site, we make a reusable component:</p>
<p>The basic layout will look like this :  <code>Header</code> -&gt; <code>Pages Content</code> -&gt; <code>Footer</code></p>
<p>Create a new file <code>Header.js</code> inside <code>src/components</code> folder. </p>
<p>In the <code>Header.js</code> file:</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span> <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">Link</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'gatsby'</span>;

export default <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>nav<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>ul className<span class="hljs-operator">=</span><span class="hljs-string">"links"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>Link to<span class="hljs-operator">=</span><span class="hljs-string">"/"</span><span class="hljs-operator">&gt;</span>Home<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>Link<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>Link to<span class="hljs-operator">=</span><span class="hljs-string">"/about"</span><span class="hljs-operator">&gt;</span>About<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>Link<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>Link to<span class="hljs-operator">=</span><span class="hljs-string">"/projects"</span><span class="hljs-operator">&gt;</span>Projects<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>Link<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>ul<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>nav<span class="hljs-operator">&gt;</span>
  )
}
</code></pre><blockquote>
<p><code>link</code> component in React means that all the routing is handled in the browser only &amp; we don't send an extra request for new pages to the server. </p>
</blockquote>
<p>Create a new file <code>Layout.js</code> inside <code>src/components</code> folder. </p>
<p>In the <code>Layout.js</code> file:</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span> <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">Header</span> <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'./Header'</span>;

export default <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Layout</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>div className<span class="hljs-operator">=</span><span class="hljs-string">"layout"</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>Header <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>div className<span class="hljs-operator">=</span><span class="hljs-string">"content"</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>h1<span class="hljs-operator">&gt;</span>Welcome to our Gatsby Site :)<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>h1<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>Gatsby <span class="hljs-keyword">is</span> known <span class="hljs-keyword">as</span> static site generator <span class="hljs-operator">!</span><span class="hljs-operator">!</span><span class="hljs-operator">!</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>hr <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        {<span class="hljs-comment">/* content for each page */</span>}
        {children}
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>  )
}
</code></pre><blockquote>
<p>In React, we can access the content inside of a component through the "children" prop.</p>
</blockquote>
<p>Now we can use this component inside our pages. So let's create a new page <code>about.js</code> inside the <strong>pages</strong> folder.</p>
<p>In the <code>about.js</code> file:</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span> <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">Layout</span> <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'../components/Layout'</span>;

export default <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">About</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>Layout<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>h3<span class="hljs-operator">&gt;</span>About page<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>h3<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>p<span class="hljs-operator">&gt;</span>description here<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>p<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>Layout<span class="hljs-operator">&gt;</span>
  )
}
</code></pre><p>Now if you go to <code>http://localhost:8000/about</code>, this will look like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642875631980/8YGnSTVtC.png" alt="Screenshot from 2022-01-22 23-07-26.png" /></p>
<p>There are lot more cool features of Gatsby which we'll explore in the next article.</p>
<h3 id="heading-wrap-up">🎯 Wrap Up!!</h3>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Different Types of Websites]]></title><description><![CDATA[In the web development world, there are many types of websites. Let's explore each of them one by one.

Static Website
Single Page Applications
Server-Side Rendering (SSR)
Static Site Generator

🎯 Static Website

Just be made of HTML pages and could...]]></description><link>https://anuradha.hashnode.dev/different-types-of-websites</link><guid isPermaLink="true">https://anuradha.hashnode.dev/different-types-of-websites</guid><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[webdev]]></category><category><![CDATA[frontend]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Mon, 10 Jan 2022 01:51:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1641752718616/fC8zUpS08.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the web development world, there are many types of websites. Let's explore each of them one by one.</p>
<ul>
<li>Static Website</li>
<li>Single Page Applications</li>
<li>Server-Side Rendering (SSR)</li>
<li>Static Site Generator</li>
</ul>
<h2 id="heading-static-website">🎯 Static Website</h2>
<ul>
<li>Just be made of HTML pages and could also include CSS and javascript</li>
<li>We have to upload HTML pages to CDN to host them on the web and whenever we request those pages in a browser it would return them to us. </li>
<li>So for every new page, we made a new request to the server. </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641751175240/CrLzE5Iz1.png" alt="static 4.png" /></p>
<h3 id="heading-advantages">✅ Advantages</h3>
<ul>
<li>Good for SEO</li>
<li>Easy to learn</li>
</ul>
<h3 id="heading-disadvantages">❌ Disadvantages</h3>
<ul>
<li>Hard to update/maintain pages (re-writing a lot of the same code on every page).</li>
<li>New request to the server is made for every page which eventually slows down the website.</li>
<li>Generally does not contain dynamic data.</li>
</ul>
<h2 id="heading-single-page-application">🎯 Single Page Application</h2>
<ul>
<li>Based on the concept of <strong>Client-Side Rendering</strong>.</li>
<li>A single-page application is an app that works inside a browser.  </li>
<li>SPAs are structured as a single HTML page that has no preloaded content.</li>
<li>Content is loaded via Javascript files for the entire application and housed within a single HTML page.</li>
<li>Only a single server request was made for the initial empty HTML page.</li>
<li>Everything else (routing, data) is handled by the SPA in the browser.</li>
<li>Typical React/ Vue applications come under this category. </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641740735930/rGfyKuLoa.png" alt="image.png" /></p>
<p>This type of website basically handles navigation in-page, without loading new pages via HTTP. A SPA website usually loads once, &amp; after that manages all links &amp; forms submission with JS through AJAX request in the background.</p>
<h3 id="heading-advantages">✅ Advantages</h3>
<ul>
<li>There is no extra request to the server for other pages which makes the website bit faster. </li>
<li>Since SPAs are component-driven so it is easy to update.</li>
</ul>
<h3 id="heading-disadvantages">❌ Disadvantages</h3>
<ul>
<li>It is not good for SEO because of load time &amp; the initial request is for a blank HTML page.</li>
</ul>
<h2 id="heading-server-side-rendering">🎯 Server-Side Rendering</h2>
<ul>
<li>HTML pages are built on the server-side after every page request.</li>
<li>Server gets the data from various sources like databases, aggregates them into template files, and then sends the resulting HTML file back to the browser. </li>
<li>PHP or Nodejs with templating engines like <code>EJS</code>, <code>jade</code>, <code>hbs</code> comes under this category.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641748425131/jlBxfwOD3.png" alt="image.png" /></p>
<h3 id="heading-advantages">✅ Advantages</h3>
<ul>
<li>Good for SEO as we get content-rich HTML back from the server on each request.</li>
<li>Easy to update</li>
</ul>
<h3 id="heading-disadvantages">❌ Disadvantages</h3>
<ul>
<li>New request to the server is made for every page.</li>
<li>Server can take time getting data from various sources &amp; rendering pages that slow down a website a little bit.</li>
</ul>
<h2 id="heading-static-site-generator">🎯 Static Site Generator</h2>
<ul>
<li>Process that takes templates, components, and data and then generates <code>static HTML</code> pages based on these things not on the server but at <strong>build time</strong> before we even deploy the application to the web.</li>
<li><strong>Gatsby</strong> with React can be used for Static-Site Generator. Other examples are <strong>Next.js</strong> or <strong>Nuxt.js</strong>.</li>
<li>Inside a Gatsby run a build command on our computer, It takes all of our React components, fetches any data that it needs and combines them, and then generates a <strong>static HTML</strong> file for each page that we have along with the Javascript bundle too.</li>
<li>Then, we just deploy all of those HTML pages &amp; Javascript to a CDN to host, so it becomes a bit like a <strong>static site</strong> at this point where each page has its own ready-made html file.</li>
<li>So, once we deployed this we'd maybe request one of these pages from the browser and the server would send it right back pretty quickly since there is no Server-side rendering involved. It's all pre-rendered HTML</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641749547508/7gszqnB_T.png" alt="ssg.png" /></p>
<ul>
<li><p>Once we have the page in the browser, the javascript bundle in that HTML page (also generated by gatsby) would kick in and the website would behave much like a Single Page Application.</p>
</li>
<li><p>Routing is handled in the browser which makes the website really quick and no extra requests for other pages are sent to the server.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641749814953/u-KBjTaXEr.png" alt="image.png" /></p>
<h3 id="heading-advantages">✅ Advantages</h3>
<ul>
<li>Better SEO, because our initial request for a page sends back a content-rich pre-rendered HTML.</li>
<li>Easy to update</li>
<li>Faster, as no extra request is made to the server.  </li>
<li>Can handle as many different data sources.</li>
</ul>
<h3 id="heading-disadvantages">❌ Disadvantages</h3>
<ul>
<li>High build time</li>
</ul>
<h2 id="heading-wrap-up">🎯 Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[How does a Browser render a Webpage?]]></title><description><![CDATA[In this article, we'll look into actions performed by a browser to render a webpage.
🎯 Steps involved in HTML page rendering:

Construction of DOM
Construction of CSSOM
Construction of Render tree
Layout Phase
Painting Phase

🎯 Construction of DOM
...]]></description><link>https://anuradha.hashnode.dev/how-does-a-browser-render-a-webpage</link><guid isPermaLink="true">https://anuradha.hashnode.dev/how-does-a-browser-render-a-webpage</guid><category><![CDATA[Web Development]]></category><category><![CDATA[browser]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[DOM]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Mon, 20 Dec 2021 09:07:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1639991552884/uHhkY2wfD.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we'll look into actions performed by a browser to render a webpage.</p>
<h2 id="heading-steps-involved-in-html-page-rendering">🎯 Steps involved in HTML page rendering:</h2>
<ol>
<li>Construction of DOM</li>
<li>Construction of CSSOM</li>
<li>Construction of Render tree</li>
<li>Layout Phase</li>
<li>Painting Phase</li>
</ol>
<h3 id="heading-construction-of-dom">🎯 Construction of DOM</h3>
<ul>
<li><p>Browser receives an HTML document from the server in the<code>binary stream format</code>, which is basically a text file with a response header <code>Content-Type = text/html; charset=UTF-8</code>.</p>
</li>
<li><p>When the browser reads the HTML document, whenever it encounters an HTML element, it creates a JS object called a <strong>Node</strong>. Eventually, all html elements will be converted to a <strong>Node</strong>.  </p>
</li>
<li><p>After the browser has created nodes from the HTML document, it has to create a "tree-like" structure of these node objects.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639942223254/opMTE9wJ9.png" alt="dom.drawio.png" /></p>
<p><strong>Document Object Model</strong> is a high-level Web API provided by the browser to efficiently render a webpage &amp; expose it publically for the developers to dynamically manipulate DOM elements for various purposes.</p>
<h3 id="heading-construction-of-cssom">🎯 Construction of CSSOM</h3>
<ul>
<li><p>After constructing the DOM, the browser reads CSS from all the sources &amp; constructs a CSSOM (CSS Object Model) - a tree-like structure.</p>
</li>
<li><p>Each node in this tree contains CSS-style information that will be copied to the DOM element it targets.</p>
</li>
<li><p>Most of the browser comes with their own stylesheet which is called <strong>user-agent stylesheets</strong>. It is a default stylesheet used by web browsers. in the absence of any CSS applied, the browser still has to render the content somehow, and the browser uses the user-agent stylesheet for that.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640073959808/1vYqb3r5B.png" alt="CSSOM-2.png" /></p>
<h3 id="heading-construction-of-render-tree">🎯 Construction of Render Tree</h3>
<ul>
<li><p>DOM &amp; CSSOM are combined together to form a Render tree that contains the nodes which have to be displayed on the page.</p>
</li>
<li><p>From the root of the DOM tree, each <strong>visible</strong> node is traversed and a respective CSSOM rule is applied. Finally, it gives the render tree containing <strong>visible</strong> nodes with content and styling. </p>
</li>
<li><p>It is a low-level representation of what will eventually get printed on the screen, it won't contain nodes that do not hold any area in the pixel matrix (like <code>head</code>, <code>meta</code>, <code>link</code> tags).</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640074387488/9q_5r7hTF.png" alt="RENDER-TREE.png" /></p>
<p>As you notice above, nodes that contain <code>display: none</code> CSS properties are not part of the render tree.</p>
<h3 id="heading-layout-phase">🎯 Layout Phase</h3>
<ul>
<li><p>This phase can be said as a <strong>geometry phase</strong>, where we calculate the geometry of the nodes.</p>
</li>
<li><p>In the layout phase, the exact position of the nodes and their size respective to the view-port of the browser is computed. In this way, a <strong>box model</strong> is generated which knows the exact positions and size. This process is also known as <strong>layout</strong> or <strong>reflow</strong>.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639943885518/Jz7bruFfF.png" alt="layout.png" /></p>
<ul>
<li>Box model generated in Layout phase:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640074982590/znytiyVvy.png" alt="box-model.png" /></p>
<h3 id="heading-painting-phase">🎯 Painting Phase</h3>
<ul>
<li>As we know the visible nodes, their styling, &amp; their geometry, now all this information is used to render the nodes from the render tree to actual pixels on the screen. This process is referred to as Painting. It uses the UI backend layer.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639944825643/nqjp1rPMo.png" alt="DOM Lifecycle.png" /></p>
<h2 id="heading-wrap-up">🎯 Wrap Up!!</h2>
<p>That's all for this article. Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Quick Guide to Typescript - Part 2]]></title><description><![CDATA[In the previous blog, we discuss some cool features of typescript. Let's continue our journey with typescript.
📌 DOM Interactions
We can use typescript to interact with the DOM. Working with DOM in typescript is as similar as in javascript. We can s...]]></description><link>https://anuradha.hashnode.dev/quick-guide-to-typescript-part-2</link><guid isPermaLink="true">https://anuradha.hashnode.dev/quick-guide-to-typescript-part-2</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[guide]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 05 Dec 2021 21:10:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638738611727/cXhKQf5Fm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <a target="_blank" href="https://anuradha.hashnode.dev/quick-guide-to-typescript-part-1">blog</a>, we discuss some cool features of typescript. Let's continue our journey with typescript.</p>
<h2 id="heading-dom-interactions">📌 DOM Interactions</h2>
<p>We can use typescript to interact with the DOM. Working with DOM in typescript is as similar as in javascript. We can still use the same query methods, event listeners &amp; we can still access the same properties of the DOM element. But there are a few key differences to be aware of.</p>
<p>Typescript automatically contains special types for every DOM element.
Let's look at the example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638717972114/aCdwkdWAd.png" alt="Screenshot from 2021-12-05 20-54-06.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638718092261/myTDLFnAU.png" alt="Screenshot from 2021-12-05 20-56-58.png" /></p>
<p>In the above example, typescript assigns special types to the variable based on the DOM element it signifies. This means whenever we use <strong>buttonTag</strong> variable, typescript knows all of the properties and methods associated with that type.</p>
<p>But what if we access the element using className or ID???</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638730519074/pq46LQbB2.png" alt="Screenshot from 2021-12-06 00-23-37.png" /></p>
<p>Now in this case, when we hover over the variable it says it is of type <strong>Element</strong> and do not point out to any specific HTML Element because the class can be applied to any different element in the HTML page, so typescript is not able to recognize its exact type.</p>
<p>So for this, we can use something known as <strong>Type Assertions</strong>.</p>
<h3 id="heading-type-assertions">📌 Type Assertions</h3>
<blockquote>
<p>Type assertion allows you to set the type of a value and tell the compiler not to infer it. </p>
</blockquote>
<p>So in our case, we can use <strong>type assertions</strong> using the keyword <strong>as</strong> to indicate a more specific type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> header = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.mainHeader'</span>) <span class="hljs-keyword">as</span> HTMLDivElement;
</code></pre>
<p>Now instead of storing it as <strong>Element</strong> type, it uses  <strong>HTMLDivElement</strong> type.</p>
<ul>
<li>Type assertions are removed by the compiler and won’t affect the runtime behavior of your code.</li>
</ul>
<p>There is one more method to use Type Assertions using <strong>angle-bracket syntax:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> header = &lt;HTMLDivElement&gt;<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.mainHeader'</span>);
</code></pre>
<h2 id="heading-tuples">📌 Tuples</h2>
<blockquote>
<p>A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.</p>
</blockquote>
<p><strong>Tuple</strong> is another built-in type that is a little bit like an array but with one major difference. In tuple, the types of data in each position are fixed once it's been initialized.</p>
<p>Let's dive into an example for a better understanding that how tuple is different from Array:</p>
<p><strong>In Arrays:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> data = [<span class="hljs-string">'javascript'</span>, <span class="hljs-number">100</span>];

data[<span class="hljs-number">0</span>] = <span class="hljs-number">20</span>;    <span class="hljs-comment">//Correct</span>
data[<span class="hljs-number">1</span>] = <span class="hljs-string">'html'</span>;   <span class="hljs-comment">//Correct</span>

data[<span class="hljs-number">0</span>] = <span class="hljs-literal">true</span>;  <span class="hljs-comment">//Error: Type 'boolean' is not assignable to type 'string | number'.</span>
</code></pre>
<p>As you can see in the above code snippet, <strong>data</strong> variable can have a mixed type of <strong>string | number</strong>. And we could reset the first position from type string to number. Which is OK in the case of Arrays. Any position in the above array can be of type <em>string</em> or <em>number</em>.</p>
<p><strong>In Tuples:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">//declare what type we expect to be in each position</span>
<span class="hljs-keyword">let</span> data : [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];

data[<span class="hljs-number">0</span>] = <span class="hljs-string">'javascript'</span>;  <span class="hljs-comment">//Correct</span>
data[<span class="hljs-number">1</span>] = <span class="hljs-number">100</span>;  <span class="hljs-comment">//Correct</span>

data[<span class="hljs-number">0</span>] = <span class="hljs-number">20</span> <span class="hljs-comment">//Error: Type 'number' is not assignable to type 'string'.</span>

data[<span class="hljs-number">2</span>] = <span class="hljs-number">30</span>; <span class="hljs-comment">//Error: Tuple type '[string, number]' of length '2' has no element at index '2'.</span>
</code></pre>
<p>In tuples, once we defined a certain position being a certain type then we cannot change that type in that position.</p>
<h2 id="heading-wrap-up">📌 Wrap Up!!</h2>
<p>That's all for this article. We'll explore more new features of typescript in the next post.
Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Quick Guide to Typescript - Part 1]]></title><description><![CDATA[Let's get started with some quick guide to Typescript.
📌 Introduction

Typescript is superset of Javascript which means it is an extension of Javascript, adding new features and syntax on top of the core language.
Typescript is a strongly typed, obj...]]></description><link>https://anuradha.hashnode.dev/quick-guide-to-typescript-part-1</link><guid isPermaLink="true">https://anuradha.hashnode.dev/quick-guide-to-typescript-part-1</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[guide]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 21 Nov 2021 19:13:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637521977572/oywyj66-C.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's get started with some quick guide to Typescript.</p>
<h2 id="heading-introduction">📌 Introduction</h2>
<ul>
<li><code>Typescript is superset of Javascript</code> which means it is an extension of Javascript, adding new features and syntax on top of the core language.</li>
<li>Typescript is a strongly typed, object-oriented &amp; compiled language.</li>
<li>Typescript is designed to be compiled into fully compatible Javascript, so it works in any browser, any host, and any OS. </li>
<li>We need typescript compiler to compile it to Javascript code because browsers do not understand typescript.</li>
<li>Typescript strongly encouraged <code>static-typing</code> which means it will validate all the assertions before the code executes. It allows you to do a type check during development which leads to the cleaner code and less errors in the browsers.</li>
</ul>
<p>If you are familiar with Javascript, then you know that javascript is a dynamic language:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// In Javascript</span>

<span class="hljs-keyword">const</span> logger = <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(msg);

<span class="hljs-keyword">let</span> marks = <span class="hljs-number">20</span>;

logger(marks);   <span class="hljs-comment">// output: 20</span>

marks = <span class="hljs-string">'twenty'</span>;

logger(marks);  <span class="hljs-comment">// output: twenty</span>
</code></pre>
<p>In the above code as you notice first we assign a value of type <code>number</code> to variable <strong>marks</strong> and then reassign it value of type <code>string</code> to the same variable.</p>
<p>This is possible in javascript because it is <code>weekly-typed language</code> which means the type of variable is figured by JS at <strong>runtime</strong> &amp; can be change from one type to another.</p>
<p>But this is not the case with typescript.</p>
<p>Let's get familiar with some unique feature which typescript provides :-</p>
<h2 id="heading-type-inference">📌 Type Inference</h2>
<blockquote>
<p>Typescript uses <strong>inference</strong> or it infers the type based on the value we assign to it.</p>
</blockquote>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">20</span>;

age = <span class="hljs-string">'twenty'</span>;  <span class="hljs-comment">// ERROR</span>
age = <span class="hljs-number">40</span>;  <span class="hljs-comment">//CORRECT</span>
</code></pre>
<p>In the above code snippet, when we try to assign a value of type "string" to variable <strong>age</strong>, it will cause error. But why???</p>
<blockquote>
<p>In Typescript, we can change the value of variables but not the type.</p>
</blockquote>
<p>When we first assign a value to variable <strong>age</strong>, we don't have to specially mention the type of the variable, typescript <em>infer</em> its type as <strong>number</strong>, which cannot be change later.</p>
<h3 id="heading-functions">🧩 Functions</h3>
<ul>
<li>We can also declare what type of a value we are expecting to be passed into the function as an arguments.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> area = <span class="hljs-function">(<span class="hljs-params">diameter: <span class="hljs-built_in">number</span></span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> diameter * <span class="hljs-built_in">Math</span>.PI
}

area(<span class="hljs-number">2</span>); <span class="hljs-comment">//Correct</span>
area(<span class="hljs-string">'two'</span>); <span class="hljs-comment">// ERROR</span>
</code></pre>
<h3 id="heading-arrays">🧩 Arrays</h3>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> marks = [<span class="hljs-number">100</span>, <span class="hljs-number">200</span>, <span class="hljs-number">300</span>, <span class="hljs-number">400</span>, <span class="hljs-number">500</span>];

<span class="hljs-comment">// marks.push('abc'); //ERROR</span>
</code></pre>
<p>In the above code snippet, typescript infers the <em>type</em> of array <strong>marks</strong> as "number", hence we cannot insert a value of type "string" into it.</p>
<p>There is another case:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> mixed = [<span class="hljs-string">'xyz'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>];

mixed[<span class="hljs-number">1</span>] = <span class="hljs-string">'abc'</span>;  <span class="hljs-comment">//Correct</span>
mixed[<span class="hljs-number">0</span>] = <span class="hljs-number">5</span>;  <span class="hljs-comment">//Correct</span>
mixed[<span class="hljs-number">3</span>] = <span class="hljs-literal">true</span>; <span class="hljs-comment">//ERROR</span>
</code></pre>
<p>In above code, typescript infers the type of array "mixed" as <strong>number</strong> or <strong>string</strong>, so we can insert the values of these types only, so in above case value of type <strong>boolean</strong> is not acceptable.</p>
<h3 id="heading-objects">🧩 Objects</h3>
<ul>
<li>Once we define the object we cannot assign additional properties to it later on.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> student = {
    name : <span class="hljs-string">'xyz'</span>,
    marks: <span class="hljs-number">30</span>
}

student.marks = <span class="hljs-number">100</span>;
student.marks = <span class="hljs-string">'30'</span> <span class="hljs-comment">//ERROR</span>

<span class="hljs-comment">//Cannot assign new property to an object</span>
student.age = <span class="hljs-number">10</span> <span class="hljs-comment">//ERROR</span>
</code></pre>
<ul>
<li>Once we declare an object then it has to have a same structure, the same type with the same set of properties which cannot be changed later on except the values.</li>
</ul>
<h2 id="heading-explicit-types">📌 Explicit Types</h2>
<ul>
<li>Typescript uses inference to know the type of the variable but we can also explicitly define the types using the following syntax:</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-comment">// Explicitly defining the types of variables</span>
<span class="hljs-keyword">let</span> character: <span class="hljs-built_in">string</span>;
<span class="hljs-keyword">let</span> totalMarks: <span class="hljs-built_in">number</span>;
<span class="hljs-keyword">let</span> isloggedIn: <span class="hljs-built_in">boolean</span>;

totalMarks = <span class="hljs-string">'200'</span>   <span class="hljs-comment">//ERROR</span>
</code></pre>
<h3 id="heading-arrays">🧩 Arrays</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// this array will contain elements of type string</span>
<span class="hljs-keyword">let</span> studentList: <span class="hljs-built_in">string</span>[ ] 

<span class="hljs-comment">// this array contains element of type number &amp; also initialising it with empty array</span>
<span class="hljs-keyword">let</span> studentMarksList: <span class="hljs-built_in">number</span>[ ] = [ ]
</code></pre>
<h3 id="heading-objects">🧩 Objects</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">//Method 1</span>
<span class="hljs-keyword">let</span> bucketList : <span class="hljs-built_in">Object</span>; 

bucketList = {
    name: <span class="hljs-string">'apple'</span>,
    price: <span class="hljs-number">30</span>
}

<span class="hljs-comment">//Method 2</span>
<span class="hljs-keyword">let</span> bucketList2: {
    name: <span class="hljs-built_in">string</span>,
    price: <span class="hljs-built_in">number</span>
}
</code></pre>
<h2 id="heading-union-types">📌 Union Types</h2>
<p>In typescript, <strong>union type</strong> allows us to define a variable with multiple type. </p>
<p>In case you want to explicitly define an array which can contain elements of type string or number, then the syntax for the same would be:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> mixedList: (<span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>)[] = [];

mixedList.push(<span class="hljs-string">'abc'</span>);
mixedList.push(<span class="hljs-number">30</span>);
<span class="hljs-comment">// mixedList.push(true); //ERROR</span>
</code></pre>
<p>Following the same rule for other variables as well</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> uid : <span class="hljs-built_in">string</span>|<span class="hljs-built_in">number</span>;
uid = <span class="hljs-string">'acc'</span>;
uid = <span class="hljs-number">10</span>;
<span class="hljs-comment">// uid = false; //ERROR</span>
</code></pre>
<h2 id="heading-dynamic-types">📌 Dynamic Types</h2>
<p>There are times when we are not sure of the exact type of specific variable. In this scenario typescript provides special type: <strong>any</strong>. This allows you to assign "any" value to that variable.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> list : <span class="hljs-built_in">any</span>;

list = <span class="hljs-number">10</span>;
list = <span class="hljs-string">'abc'</span>;

<span class="hljs-keyword">let</span> countList : <span class="hljs-built_in">any</span>[] = [];
countList.push(<span class="hljs-number">10</span>);
countList.push(<span class="hljs-string">'xyz'</span>);
</code></pre>
<h2 id="heading-functions-in-typescript">📌 Functions in Typescript</h2>
<ul>
<li>In Typescript we can either use an arrow functions or a regular functions.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> greet: <span class="hljs-built_in">Function</span>
greet = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hello world"</span>);
}

<span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">a:<span class="hljs-built_in">number</span>, b: <span class="hljs-built_in">number</span></span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"sum = "</span>, a + b);
}

add(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>);
</code></pre>
<ul>
<li>you can define <strong>optional parameter</strong> inside a function using the syntax:</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> subtract = <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y: <span class="hljs-built_in">number</span>, z?: <span class="hljs-built_in">string</span>|<span class="hljs-built_in">number</span></span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"difference-&gt; "</span>, x-y);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"optional parameter-&gt; "</span>, z );
}

subtract(<span class="hljs-number">10</span>, <span class="hljs-number">5</span>);
subtract(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, <span class="hljs-number">30</span>);
subtract(<span class="hljs-number">100</span>,<span class="hljs-number">50</span>, <span class="hljs-string">'abc'</span>);
</code></pre>
<p>Always put your required parameters at first and then put the optional parameters at the end.</p>
<ul>
<li>define <strong>default value</strong> of a parameter inside a function :</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> multiply = <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span> = <span class="hljs-number">10</span></span>) =&gt;</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"default value parameter-&gt; "</span>, x );
}

multiply(); <span class="hljs-comment">// 10</span>
multiply(<span class="hljs-number">20</span>); <span class="hljs-comment">//20</span>
</code></pre>
<ul>
<li>When a function returns something, typescript will infer the return type automatically.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> divide = <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span>, y:<span class="hljs-built_in">number</span></span>)=&gt;</span>{
    <span class="hljs-keyword">return</span> x/y;
}

<span class="hljs-comment">//Typescript automatically infer the type of result as number</span>
<span class="hljs-keyword">const</span> result = divide(<span class="hljs-number">20</span>,<span class="hljs-number">10</span>);
</code></pre>
<ul>
<li>You can also explicitly define the <strong>return type</strong> of function by using the syntax:</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> msg = ():<span class="hljs-function"><span class="hljs-params">string</span> =&gt;</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'hello world'</span>;
}

<span class="hljs-keyword">const</span> greeting = msg();
</code></pre>
<ul>
<li>function in Typescript will return a <strong>void</strong> value when function doesn't return something. <strong>void</strong> is completely different from <strong>undefined</strong> in javascript.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-comment">// Function Signature</span>
<span class="hljs-keyword">let</span> calculateFn: <span class="hljs-function">(<span class="hljs-params">x: <span class="hljs-built_in">number</span></span>) =&gt;</span> <span class="hljs-built_in">void</span> 

calculateFn = <span class="hljs-function">(<span class="hljs-params">num: <span class="hljs-built_in">number</span></span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"num-&gt; "</span>, num)
}

calculateFn(<span class="hljs-number">10</span>);
</code></pre>
<h2 id="heading-type-aliases">📌 Type Aliases</h2>
<p>We can initially defined the type which can be reusable later on with the keyword <strong>type</strong>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> stringOrNumber = <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>;
<span class="hljs-keyword">const</span> myPredefinedType: stringOrNumber = <span class="hljs-number">10</span>;

<span class="hljs-keyword">type</span> personRecord = {
    name: <span class="hljs-built_in">string</span>,
    marks: stringOrNumber
}

<span class="hljs-keyword">let</span> obj : personRecord;
obj = {
    name: <span class="hljs-string">'anu'</span>,
    marks: <span class="hljs-string">'100'</span>
}
</code></pre>
<p>In the above code snippet, we have define two types <strong>stringOrNumber</strong> &amp; <strong>personRecord</strong>, which are reused later on.</p>
<h2 id="heading-wrap-up">📌 Wrap Up!!</h2>
<p>That's all for this article. We'll explore more new features of typescript in the next post.
Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a></p>
]]></content:encoded></item><item><title><![CDATA[BEM Methodology]]></title><description><![CDATA[Hola Friends, In this article we'll learn about BEM Methodology.
What is BEM ?

BEM divides the layout into 3 main parts: - Block - Element - Modifier

It's a CSS naming convention for writing cleaner and more readable CSS classes. BEM also aims to w...]]></description><link>https://anuradha.hashnode.dev/bem-methodology</link><guid isPermaLink="true">https://anuradha.hashnode.dev/bem-methodology</guid><category><![CDATA[CSS]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[best practices]]></category><category><![CDATA[CSS Frameworks]]></category><category><![CDATA[HTML5]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 05 Sep 2021 21:16:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1630875672722/tYlCsUCto.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hola Friends, In this article we'll learn about BEM Methodology.</p>
<h2 id="heading-what-is-bem">What is BEM ?</h2>
<ul>
<li><p>BEM divides the layout into 3 main parts: - <strong>Block</strong> - <strong>Element</strong> - <strong>Modifier</strong></p>
</li>
<li><p>It's a CSS naming convention for writing cleaner and more readable CSS classes. BEM also aims to write independent CSS blocks to reuse them later in your project.</p>
</li>
<li><p>BEM is ideal for teams of developers on larger projects where designers and developers consistently name components for easier communication between the team members.</p>
</li>
<li><p>BEM syntax usually looks like this: </p>
</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-class">.block__element--modifier</span>
</code></pre>
<p>Let's explore this in more detail:</p>
<h3 id="heading-block">Block</h3>
<p>Encapsulates a standalone entity that is meaningful on its own. It is usually a bigger component of a webpage. for example header, card, div, etc.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>= <span class="hljs-string">"card"</span>&gt;</span>
. . .
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-element">Element</h3>
<p>It is a part of a block and has no standalone meaning. Any element is semantically tied to its block. It is represented using <code>[block-name](double underscore)[element-name]</code> like <code>card__header</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>= <span class="hljs-string">"card"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>= <span class="hljs-string">"card__header"</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">"card__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">div</span>&gt;</span>
</code></pre>
<p>In the above example, <code>card__header</code> &amp; <code>card__body</code> represents the <strong>Elements</strong> which resides inside the <strong>Block</strong> <code>card</code>.</p>
<h3 id="heading-modifiers">Modifiers</h3>
<p>It represents the flags on blocks or elements. Use them to change appearance, behavior, or state.</p>
<p>A modifier is an extension that specifies some change in the style of the block or the element it is applied to.</p>
<p>A modifier is indicated by using <code>double dashes</code> after the class name which allows you to overwrite the styles for a specific type of block, or an element.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn--active"</span>&gt;</span> Click Me <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">class</span>=<span class="hljs-string">"btn btn--disabled"</span>&gt;</span> Clicked <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In the above code snippet, <code>btn--active</code> &amp; <code>btn--disabled</code> represents the <strong>Modifiers</strong>.</p>
<p>Corresponding CSS code would be:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.card</span> { ... }
<span class="hljs-selector-class">.card__header</span> { ... }
<span class="hljs-selector-class">.card__body</span> { ... }

<span class="hljs-selector-class">.btn</span> { ... }
<span class="hljs-selector-class">.btn--active</span> { ... }
<span class="hljs-selector-class">.btn--disabled</span> { ... }
</code></pre>
<p>In case you are using some CSS preprocessor, you can modify your CSS file in the following way:</p>
<pre><code class="lang-CSS">
<span class="hljs-selector-class">.card</span> {
    &amp;__header { . . . }
    &amp;__<span class="hljs-selector-tag">body</span> { . . . }
}

<span class="hljs-selector-class">.btn</span> {
    &amp;--active { . . . }
    &amp;<span class="hljs-selector-tag">--disabled</span> { . . . }
}
</code></pre>
<p>BEM makes our CSS easier to read, helps to write clean code, and also saves a lot of time to decide the class name.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p>http://getbem.com/naming/</p>
</li>
<li><p>https://9elements.com/bem-cheat-sheet/</p>
</li>
</ul>
<h2 id="heading-wrap-up">Wrap Up!!</h2>
<p>Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a>  </p>
]]></content:encoded></item><item><title><![CDATA[A Complete Guide to Redux]]></title><description><![CDATA[Hello coders!! Today we will discuss some concepts you need to know to build real complex applications with React and Redux.
In this article we'll cover the following concepts in detail:

Why we need redux?
What is Redux?
Steps to create a React-redu...]]></description><link>https://anuradha.hashnode.dev/a-complete-guide-to-redux</link><guid isPermaLink="true">https://anuradha.hashnode.dev/a-complete-guide-to-redux</guid><category><![CDATA[Redux]]></category><category><![CDATA[Javascript library]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[100DaysOfCode]]></category><dc:creator><![CDATA[Anuradha Aggarwal]]></dc:creator><pubDate>Sun, 30 May 2021 22:21:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622413020762/_QK7LeKon.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello coders!! Today we will discuss some concepts you need to know to build real complex applications with React and Redux.</p>
<p>In this article we'll cover the following concepts in detail:</p>
<ul>
<li>Why we need redux?</li>
<li>What is Redux?</li>
<li>Steps to create a React-redux application<ul>
<li>Step 1: Create a User Component</li>
<li>Step 2: Create a Store</li>
<li>Step 3: Create a Reducer</li>
<li>Step 4: Share Redux Store with Components</li>
<li>Step 5: Add an Async Function Middleware using Redux Thunk</li>
<li>Step 6: Build an Action Creator</li>
<li>Step 7: Connect redux store to components</li>
</ul>

</li>
</ul>
<p>Let's get started!! 🚀🚀</p>
<h2 id="heading-why-redux">Why Redux?</h2>
<p>Before we jump to more details of Redux first try to understand why we actually need it?</p>
<p>In a complex application with many components, if you want to share a <strong>state</strong> among the several components, then one approach you can think of is using <strong>props</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621174749897/mid2qN1xz.png" alt="image.png" /></p>
<p>But <strong>props</strong> doesn't solve our problem completely as it only enables you to send data from a parent component to a child component using the <strong>top-down approach</strong> and not vice-versa. That means any change in the state that occurred in the child component does not impact the parent component's state. </p>
<p>Also, another problem that <strong>props</strong> failed to solve is to share the state among the components with no parent-child hierarchy.</p>
<p>So, to overcome all the above problems and to synchronize the state across the components <strong>Redux</strong> comes into the picture. Using this approach we store all the state globally and all other components can access it.</p>
<p><strong>Redux</strong> is an open-source JavaScript library for managing the application state.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621177830450/I-0w4YenH.png" alt="image.png" /></p>
<h2 id="heading-what-is-redux">What is Redux?</h2>
<ul>
<li>Redux is basically used for state management. </li>
<li>It can be used with all javascript frameworks &amp; libraries like React, angular, etc.</li>
</ul>
<p>Main Elements of Redux includes:-</p>
<ul>
<li><strong>Store:</strong>  If you are working on a large application, the state is separated from the React components into its own <strong>store</strong>. The store is the global component that stores the current state and it is an immutable object.</li>
<li><strong>Action: </strong>  State in the store is not changed directly, but with different <strong>actions</strong>. </li>
<li><strong>Reducer: </strong> It is used to define the impact of the action on the state of the application.</li>
<li><strong>Subscribe:</strong> It is used to create a callback function the store calls when its state is changed.</li>
</ul>
<p>Redux Principles:</p>
<ul>
<li>The global state of your application is stored as an object inside a <strong>single store.</strong></li>
<li>The only way to change the state is to <code>dispatch</code> an action.</li>
<li>Changes are made with pure reducer functions.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621184602504/h5JWu6pt3.png" alt="image.png" /></p>
<p>Let's explore each one of them in detail by using a simple example:</p>
<p>We'll follow the following Folder structure:  </p>
<pre><code>📦src
 ┣ 📂actions
 ┃ ┣ 📜types.js
 ┃ ┗ 📜users.js
 ┣ 📂components
 ┃ ┗ 📂Users
 ┃ ┃ ┣ 📜index.js
 ┃ ┃ ┗ 📜user.css
 ┣ 📂reducers
 ┃ ┣ 📜index.js
 ┃ ┗ 📜users.js
 ┣ 📂store
 ┃ ┗ 📜index.js
 ┣ 📜App.js
 ┗ 📜index.js
</code></pre><p>You can find the final code in my <a target="_blank" href="https://github.com/anuradha9712/react-redux-application">github repo</a></p>
<p>Now we will create an application that fetches user data using REST APIs and display it using Redux.</p>
<p>In the end, our application will look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622409093180/jvUNBvBLa.gif" alt="GifMaker_20210531023908270.gif" /></p>
<p>Create a React application and install redux using <code>npm install react-redux --save</code>.</p>
<h3 id="heading-step-1-create-a-user-component">Step 1: Create a User Component</h3>
<p>In <code>src/components/Users/index.js</code> file: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./user.css'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Users</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">const</span> [userDetails, setUserDetails] = useState([]);

    <span class="hljs-keyword">const</span> handleButtonClick = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// make a call to Action Creator</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">"container"</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"click me"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleButtonClick}</span>&gt;</span>
                 Fetch Data
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Id<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Phone<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Website<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
                    {
                        userDetails &amp;&amp; userDetails.map((item, key) =&gt; {
                            return (
                                <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>{item.id}<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>{item.name}<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>{item.phone}<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>{item.email}<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>{item.website}<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
                                <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
                            )
                        })
                    }
                <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<p>In the above code, we'll make an API call to fetch our data using REST API whenever a user clicks on the button and display the data in table format. </p>
<p>But before making an API call let's set up our <strong>store</strong> first.</p>
<h3 id="heading-step-2-create-a-store">Step 2: Create a Store</h3>
<p>we'll create a <strong>Redux store</strong> in <code>src/store/index.js</code> file: </p>
<pre><code><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> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducers"</span>;

<span class="hljs-keyword">const</span> preloadedState = {};

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store;
</code></pre><ul>
<li>The Redux core library has a <strong>createStore</strong> API that will create the store. </li>
<li>We'll pass our <em>rootReducer</em> that we'll create in the next step as an argument.  </li>
<li><strong>createStore</strong> can also accept a <em>preloadedState</em> value as its second argument. You could use this to add initial data when the store is created.</li>
</ul>
<p><strong>Points to remember:</strong></p>
<ul>
<li>The store basically brings together the <code>state</code>, <code>actions</code>, and <code>reducers</code> that make up your app.</li>
<li>You can only have a single store in a Redux application.</li>
<li>Every Redux store has a single root reducer function.</li>
</ul>
<h3 id="heading-step-3-create-a-reducer">Step 3: Create a Reducer</h3>
<ul>
<li>Reducers basically tell us how to update the <em>state</em> based on the <em>action</em> performed.</li>
<li>It must be <strong>pure functions</strong> &amp; should not produce any side effects.</li>
<li>It must be composed of <em>immutable</em> objects. If there is a change in the state, the old object is not changed, but it is replaced with a new, changed object.  </li>
</ul>
<p>Let's create our reducer in <code>src/reducers/user.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { USER_DETAILS } <span class="hljs-keyword">from</span> <span class="hljs-string">'../actions/types'</span>;

<span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">userDetails</span>: {}
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">state = initialState, action</span>) </span>{

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 4: Inside User Reducer after action creator dispatches an action"</span>);
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> USER_DETAILS:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">userDetails</span>: action.payload,
      };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
}
</code></pre>
<p>It is a function that is given the current state and an action as a parameter it returns a new state.</p>
<p>Now we have created one reducer but as our application becomes more complex we may need to introduce more reducers. </p>
<p>So in this case, we'll create the main <strong>root Reducer</strong> which will combine all other reducers used in our application.</p>
<p>In <code>src/reducers/index.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { combineReducers } <span class="hljs-keyword">from</span> <span class="hljs-string">"redux"</span>;
<span class="hljs-keyword">import</span> userReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"./users"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> combineReducers({
    <span class="hljs-attr">userReducer</span>: userReducer,
   <span class="hljs-comment">//other reducers</span>
});
</code></pre>
<p>we can create the actual reducer for our application by combining the two or many existing reducers with the <strong>combineReducers</strong> function.</p>
<p>The <strong>combineReducer</strong> works in such a way that every <em>action</em> gets handled in every part of the combined reducer. Typically only one reducer is interested in any given action, but there are situations where multiple reducers change their respective parts of the state based on the same action.</p>
<h3 id="heading-step-4-share-redux-store-with-components">Step 4: Share Redux Store with Components</h3>
<p>As we have initially created our store, the next step is to make it available to all the components present in our application.  </p>
<p>In <code>src/App.js</code> file:</p>
<pre><code class="lang-javascript"><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> store <span class="hljs-keyword">from</span> <span class="hljs-string">'./store'</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> Users <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Users'</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">Users</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>By using this way. all the components can access the store.</p>
<h3 id="heading-step-5-add-an-async-function-middleware-using-redux-thunk">Step 5: Add an Async Function Middleware using Redux Thunk</h3>
<p>After setting up the store, now we need to make an API call to fetch our data but before this, we will add middleware to our store which enables us to create an asynchronous action.</p>
<p><strong>Redux Thunk</strong></p>
<p>This library is a so-called redux-middleware, which must be initialized along with the initialization of the store. </p>
<p>Because of this, it is possible to define <em>action-creators</em> so that they return a function having the <strong>dispatch</strong> method of redux-store as its parameter. </p>
<p>As a result of this, one can make asynchronous action-creators, which first wait for some operations to finish, after which they then dispatch the real action.</p>
<p>To introduce redux-thunk into our application first install it using <code>npm install --save redux-thunk</code>.</p>
<p>Now in <code>src/store/index.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createStore, applyMiddleware, compose } <span class="hljs-keyword">from</span> <span class="hljs-string">"redux"</span>;
<span class="hljs-keyword">import</span> thunk <span class="hljs-keyword">from</span> <span class="hljs-string">"redux-thunk"</span>;
<span class="hljs-keyword">import</span> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducers"</span>;

<span class="hljs-keyword">const</span> preloadedState = {};

<span class="hljs-keyword">const</span> middleware = [thunk];
<span class="hljs-keyword">const</span> composeEnhancers = <span class="hljs-built_in">window</span>.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

<span class="hljs-keyword">const</span> store = createStore(
    rootReducer,
    preloadedState,
    composeEnhancers(
        applyMiddleware(...middleware)
    )
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store;
</code></pre>
<p>As you noticed we introduce many new terms in the above code. Let's try to explore each one of them one by one.</p>
<p><strong>compose</strong></p>
<p>compose is an example of <strong>higher-order functions</strong>. It takes bunch of functions as arguments and returns a new function that is the composition of all these functions.</p>
<ul>
<li>It is used when you want to pass multiple <em>store-enhancers</em> to the store.</li>
<li>It composes single-argument functions from right to left. The rightmost function can take multiple arguments as it provides the signature for the resulting composite function. for example: 
<code>compose(f, g, h)</code> is identical to doing <code>(...args) =&gt; f(g(h(...args)))</code>.</li>
</ul>
<p><strong>store enhancers</strong></p>
<ul>
<li>They are <em>higher-order functions</em> that add some extra functionality to the store. The only store enhancer which is supplied with redux by default is <em>applyMiddleware</em>.</li>
</ul>
<p><strong>applyMiddleware</strong></p>
<ul>
<li>Creates a store enhancer that applies middleware to the <strong>dispatch</strong> method of the Redux store. This is handy for a variety of tasks, such as expressing asynchronous actions in a concise manner or logging every action payload.</li>
<li>Because middleware is potentially asynchronous, this should be the first store enhancer in the composition chain.</li>
</ul>
<p>We'll see the use of <strong>dispatch</strong> in the next step.</p>
<h3 id="heading-step-6-build-an-action-creator">Step 6: Build an Action Creator</h3>
<p>Now it's time to make an action creator which fetches data using REST APIs.</p>
<p>Action creators are a <strong>pure function</strong> which creates action.</p>
<p><strong>Actions</strong> are plain JS objects that have a <code>type</code> field and can contain additional data. It creates an event that describes something that happened in the application.</p>
<p>We'll declare all the <code>type</code> field in a separate file <code>src/actions/types.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> USER_DETAILS = <span class="hljs-string">'USER_DETAILS'</span>;
</code></pre>
<p>To build an Action creator:-</p>
<p>In <code>src/actions/user.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;
<span class="hljs-keyword">import</span> { USER_DETAILS } <span class="hljs-keyword">from</span> <span class="hljs-string">'./types'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getUserDetails = <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">async</span> (dispatch) =&gt; {

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 2: Inside Action Creator to make an API call"</span>);
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>);

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 3: Dispatch an Action to update the state"</span>);
    dispatch({
        <span class="hljs-attr">type</span>: USER_DETAILS,
        <span class="hljs-attr">payload</span>: res
    })
}
</code></pre>
<p>In the above code snippet, we make an API call, and as soon as we get our response we <strong>dispatch</strong> the action so we can change the state. </p>
<p>The store now uses the <strong>reducer</strong> to handle <strong>actions</strong>, which are dispatched or 'sent' to the store with its <strong>dispatch</strong> method.</p>
<h3 id="heading-step-7-connect-redux-store-to-components">Step 7: Connect redux store to components</h3>
<p>We have finally done with the store setup. We are one step away so just follow up 🤓🤓. </p>
<p>In <code>src/components/Users/index.js</code> file: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { getUserDetails } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../actions/users'</span>;
<span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./user.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Users</span>(<span class="hljs-params">{ getUserDetails, userReducer }</span>) </span>{

    <span class="hljs-keyword">const</span> [userDetails, setUserDetails] = useState([]);

    <span class="hljs-keyword">const</span> handleButtonClick = <span class="hljs-function">() =&gt;</span> {

        <span class="hljs-comment">//make a call to the Action creator</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 1: Make a call to Action-creator from Users Component"</span>);
        getUserDetails();
    }

    useEffect(<span class="hljs-function">() =&gt;</span> {

        <span class="hljs-comment">// Update the UI as soon as we get our response through API call</span>
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Step 5: Inside UseEffect of User Component to update the UI"</span>)
        setUserDetails(userReducer.userDetails.data);
    }, [userReducer.userDetails])

    <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">"container"</span>&gt;</span>
          .....
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">const</span> mapStateToProps = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> ({
    <span class="hljs-attr">userReducer</span>: state.userReducer
});

<span class="hljs-keyword">const</span> mapDispatchToProps = {
    getUserDetails
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> connect(mapStateToProps, mapDispatchToProps)(Users);
</code></pre>
<p>In the above code snippet, we share the redux store with components with the help of <code>connect</code>.</p>
<blockquote>
<p>Higher-order components are a function that accepts a "regular" component as its parameter and returns a new "regular" component as its return value.</p>
</blockquote>
<p><strong>connect</strong></p>
<ul>
<li><p><em>connect</em> method provided by react-redux is an example of <strong>Higher-order components</strong>.</p>
</li>
<li><p><em>connect</em> method is used for transforming the "regular" React component so that the state of the Redux store can be "mapped" into the component's props.</p>
</li>
<li><p>It accepts two parameters: <code>mapStateToProps</code> and <code>mapDispatchToProps</code>.</p>
</li>
</ul>
<p><strong>mapStateToProps</strong></p>
<p>It is a function that can be used for defining the props of the connected component that are based on the state of the Redux store.</p>
<p><strong>mapDispatchToProps</strong></p>
<ul>
<li>It is a JS object of action-creators functions passed to the connected components as props.</li>
<li>The functions passed in <em>mapDispatchToProps</em> must be action creators, i.e. functions that returns Redux actions.</li>
</ul>
<p>As you noticed how we can pass our <em>action creators</em> and <em>redux state</em> as a parameter to the <em>Users</em> component.</p>
<p>On button click, we invoke action-creator which makes an API call and update the redux state.
In <code>useEffect</code> we will monitor the change in redux state and update the UI with response data.</p>
<p>Finally, our React application with Redux is ready!!! 😎😎</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622408091353/JRvs9DBnQ.gif" alt="react-redux.gif" /></p>
<p>We can use the <strong>Redux Devtools</strong> to test and debug how Redux states are changing.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622568656661/9X-yr80Yz.png" alt="image.png" /></p>
<p>You can find the final code in my <a target="_blank" href="https://github.com/anuradha9712/react-redux-application">github repo</a></p>
<h2 id="heading-wrap-up">Wrap Up!!</h2>
<p>Thank you for your time!! Let's connect to learn and grow together.</p>
<p><a target="_blank" href="https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/">LinkedIn</a> <a target="_blank" href="https://twitter.com/Anuradh06359394">Twitter</a> <a target="_blank" href="https://www.instagram.com/blogcode404/">Instagram</a></p>
<p><a target="_blank" href="https://www.buymeacoffee.com/anuradha2612"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" /></a>  </p>
]]></content:encoded></item></channel></rss>