<?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[Bits to Qubits]]></title><description><![CDATA[I am a Full stack web developer with passion for computer science, physics and stories. I publish articles on my learning and interests.]]></description><link>https://bitstoqubits.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 13 Oct 2026 10:13:35 GMT</lastBuildDate><atom:link href="https://bitstoqubits.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Writing conditional tailwind classNames.]]></title><description><![CDATA[You want to add a style to a div when a particular state in your app is true? You can achieve this using this library.
In your Next.js or React app create a folder in root directory and name it as "lib". Inside lib folder create a file named "utils.t...]]></description><link>https://bitstoqubits.hashnode.dev/writing-conditional-tailwind-classnames</link><guid isPermaLink="true">https://bitstoqubits.hashnode.dev/writing-conditional-tailwind-classnames</guid><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[Satishkumar]]></dc:creator><pubDate>Thu, 25 Jan 2024 15:01:37 GMT</pubDate><content:encoded><![CDATA[<p>You want to add a style to a div when a particular state in your app is true? You can achieve this using this library.</p>
<p>In your Next.js or React app create a folder in root directory and name it as "lib". Inside lib folder create a file named "utils.ts" or "utils.js" based on the language of your choice.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706187197976/bfe393ef-7fb7-4c82-8521-08f688fc9116.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-installing-packages">Installing packages</h2>
<p>Run this below command to install these npm package:</p>
<pre><code class="lang-bash">npm i clsx
npm i tailwind-merge
</code></pre>
<h2 id="heading-below-its-explained-what-these-libraries-do-skip-this-section-if-not-interested">Below it's explained what these libraries do? skip this section if not interested.</h2>
<h3 id="heading-tailwind-merge">Tailwind Merge.</h3>
<p>If you use Tailwind CSS with a component-based UI renderer like <a target="_blank" href="https://reactjs.org">React</a> or <a target="_blank" href="https://vuejs.org">Vue</a>, you're probably familiar with the situation that you want to change some styles of a component, but only in a one-off case.</p>
<pre><code class="lang-bash">// React components with JSX syntax used <span class="hljs-keyword">in</span> this example

<span class="hljs-keyword">function</span> MyGenericInput(props) {
    const className = `border rounded px-2 py-1 <span class="hljs-variable">${props.className || ''}</span>`
    <span class="hljs-built_in">return</span> &lt;input {...props} className={className} /&gt;
}

<span class="hljs-keyword">function</span> MyOneOffInput(props) {
    <span class="hljs-built_in">return</span> (
        &lt;MyGenericInput
            {...props}
            className=<span class="hljs-string">"p-3"</span> // ← Only want to change some padding
        /&gt;
    )
}
</code></pre>
<p>When <code>MyOneOffInput</code> is rendered, an input with the className <code>border rounded px-2 py-1 p-3</code> gets created. But because of the way the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/Cascade">CSS cascade</a> works, the styles of the <code>p-3</code> class are ignored. The order of the classes in the <code>className</code> string doesn't matter at all and the only way to apply the <code>p-3</code> styles is to remove both <code>px-2</code> and <code>py-1</code>.</p>
<p>This is where tailwind-merge comes in.</p>
<pre><code class="lang-bash"><span class="hljs-keyword">function</span> MyGenericInput(props) {
    // ↓ Now `props.className` can override conflicting classes
    const className = twMerge(<span class="hljs-string">'border rounded px-2 py-1'</span>, props.className)
    <span class="hljs-built_in">return</span> &lt;input {...props} className={className} /&gt;
}
</code></pre>
<p>tailwind-merge overrides conflicting classes and keeps everything else untouched. In the case of the <code>MyOneOffInput</code>, the input is now rendered with the classes <code>border rounded p-3</code>.</p>
<h3 id="heading-clsx">CLSX:</h3>
<h3 id="heading-usage">Usage</h3>
<pre><code class="lang-bash">import clsx from <span class="hljs-string">'clsx'</span>;
// or
import { clsx } from <span class="hljs-string">'clsx'</span>;

// Strings (variadic)
clsx(<span class="hljs-string">'foo'</span>, <span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-string">'bar'</span>, <span class="hljs-string">'baz'</span>);
//=&gt; <span class="hljs-string">'foo bar baz'</span>

// Objects
clsx({ foo:<span class="hljs-literal">true</span>, bar:<span class="hljs-literal">false</span>, baz:isTrue() });
//=&gt; <span class="hljs-string">'foo baz'</span>

// Objects (variadic)
clsx({ foo:<span class="hljs-literal">true</span> }, { bar:<span class="hljs-literal">false</span> }, null, { <span class="hljs-string">'--foobar'</span>:<span class="hljs-string">'hello'</span> });
//=&gt; <span class="hljs-string">'foo --foobar'</span>

// Arrays
clsx([<span class="hljs-string">'foo'</span>, 0, <span class="hljs-literal">false</span>, <span class="hljs-string">'bar'</span>]);
//=&gt; <span class="hljs-string">'foo bar'</span>

// Arrays (variadic)
clsx([<span class="hljs-string">'foo'</span>], [<span class="hljs-string">''</span>, 0, <span class="hljs-literal">false</span>, <span class="hljs-string">'bar'</span>], [[<span class="hljs-string">'baz'</span>, [[<span class="hljs-string">'hello'</span>], <span class="hljs-string">'there'</span>]]]);
//=&gt; <span class="hljs-string">'foo bar baz hello there'</span>

// Kitchen sink (with nesting)
clsx(<span class="hljs-string">'foo'</span>, [1 &amp;&amp; <span class="hljs-string">'bar'</span>, { baz:<span class="hljs-literal">false</span>, bat:null }, [<span class="hljs-string">'hello'</span>, [<span class="hljs-string">'world'</span>]]], <span class="hljs-string">'cya'</span>);
//=&gt; <span class="hljs-string">'foo bar hello world cya'</span>
</code></pre>
<h3 id="heading-api">API</h3>
<h3 id="heading-clsxhttpsgithubcomlukeedclsxapiinput">cl<a target="_blank" href="https://github.com/lukeed/clsx#API">sx(..</a>.input)</h3>
<p>Retu<a target="_blank" href="https://github.com/lukeed/clsx#API">rns</a>: <code>String</code></p>
<h4 id="heading-inputhttpsgithubcomlukeedclsxapi">in<a target="_blank" href="https://github.com/lukeed/clsx#API">put</a></h4>
<p>Type<a target="_blank" href="https://github.com/lukeed/clsx#API">: <code>M</code></a><code>ixed</code></p>
<p>The <a target="_blank" href="https://github.com/lukeed/clsx#API"><code>cls</code></a><code>x</code> function can take <strong><em>any</em></strong> number of arguments, each of which can be an Object, Array, Boolean, or String.</p>
<blockquote>
<p><strong>Impo</strong><a target="_blank" href="https://github.com/lukeed/clsx#API"><strong>rta</strong></a>**nt:**<em>Any</em> falsey values are discarded!<br />Standalone Boolean values are discarded as well.</p>
</blockquote>
<pre><code class="lang-bash">clsx(<span class="hljs-literal">true</span>, <span class="hljs-literal">false</span>, <span class="hljs-string">''</span>, null, undefined, 0, NaN);
//=&gt; <span class="hljs-string">''</span>
</code></pre>
<h3 id="heading-modeshttpsgithubcomlukeedclsxapi">Mo<a target="_blank" href="https://github.com/lukeed/clsx#API">des</a></h3>
<p>Ther<a target="_blank" href="https://github.com/lukeed/clsx#API">e a</a>re multiple "versions" of <code>clsx</code> available, which allows you to bring only the functionality you need!</p>
<h4 id="heading-clsxhttpsgithubcomlukeedclsxapi"><code>cl</code><a target="_blank" href="https://github.com/lukeed/clsx#API"><code>sx</code></a></h4>
<blockquote>
<p><strong>Size</strong><a target="_blank" href="https://github.com/lukeed/clsx#API"><strong>(g</strong></a><strong>zip):</strong> 239 bytes<br /><strong>Availability:</strong> CommonJS, ES Module, UMD</p>
</blockquote>
<p>The <a target="_blank" href="https://github.com/lukeed/clsx#API">def</a>ault <code>clsx</code> module; see <a target="_blank" href="https://github.com/lukeed/clsx#API">API</a> for info.</p>
<pre><code class="lang-bash">import { clsx } from <span class="hljs-string">'clsx'</span>;
// or
import clsx from <span class="hljs-string">'clsx'</span>;
</code></pre>
<h4 id="heading-clsxlihttpsgithubcomlukeedclsxapite"><code>cl</code><a target="_blank" href="https://github.com/lukeed/clsx#API"><code>sx/li</code></a><code>te</code></h4>
<blockquote>
<p><strong>Size</strong><a target="_blank" href="https://github.com/lukeed/clsx#API"><strong>(g</strong></a><strong>zip):</strong> 140 bytes<br /><strong>Availability:</strong> CommonJS, ES Module<br /><strong>CAUTION:</strong> Accepts <strong>ONLY</strong> string arguments!</p>
</blockquote>
<p>Idea<a target="_blank" href="https://github.com/lukeed/clsx#API">l f</a>or applications that <strong><em>only</em></strong> use the string-builder pattern.</p>
<p>Any <a target="_blank" href="https://github.com/lukeed/clsx#API">non</a>-string arguments are ignored!</p>
<pre><code class="lang-bash">import { clsx } from <span class="hljs-string">'clsx/lite'</span>;
// or
import clsx from <span class="hljs-string">'clsx/lite'</span>;

// string
clsx(<span class="hljs-string">'hello'</span>, <span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-string">'foo'</span>, <span class="hljs-literal">false</span> &amp;&amp; <span class="hljs-string">'bar'</span>);
// =&gt; <span class="hljs-string">"hello foo"</span>

// NOTE: Any non-string input(s) ignored
clsx({ foo: <span class="hljs-literal">true</span> });
//=&gt; <span class="hljs-string">"</span>
</code></pre>
<h2 id="heading-after-installing-the-above-packages-paste-this-code-in-utilsts-file">After installing the above packages, paste this code in utils.ts file.</h2>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { <span class="hljs-keyword">type</span> ClassValue, clsx } <span class="hljs-keyword">from</span> <span class="hljs-string">"clsx"</span>
<span class="hljs-keyword">import</span> { twMerge } <span class="hljs-keyword">from</span> <span class="hljs-string">"tailwind-merge"</span>

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cn</span>(<span class="hljs-params">...inputs: ClassValue[]</span>) </span>{
  <span class="hljs-keyword">return</span> twMerge(clsx(inputs))
}
</code></pre>
<h2 id="heading-now-we-will-create-a-component-to-understand-how-we-can-use-this-cn-function-we-created">Now we will create a component to understand how we can use this cn function we created.</h2>
<p>Our goal is to create a button that changes it's color from blue to green or green to blue when clicked on it. The completed work will look like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706192356757/ade64088-1de9-41eb-acf2-bfb1789efef3.gif" alt class="image--center mx-auto" /></p>
<p>Now create a file named "Demo.tsx" and paste this below code in it.</p>
<pre><code class="lang-typescript"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">interface</span> DemoProps {}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Demo = <span class="hljs-function">(<span class="hljs-params">{}: DemoProps</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [state, setState] = useState(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">return</span> (
    &lt;div className=<span class="hljs-string">'flex'</span>&gt;
      &lt;button
        <span class="hljs-keyword">type</span>=<span class="hljs-string">'button'</span>
        className=<span class="hljs-string">'text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800'</span>
      &gt;
        Click me to change the color <span class="hljs-keyword">of</span> me
      &lt;/button&gt;
    &lt;/div&gt;
  );
};
</code></pre>
<p>Add this above component to your main component, in our case it's: 'src/app/page.tsx'.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Demo } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/components/Demo'</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">Home</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    &lt;main className=<span class="hljs-string">'w-full h-screen flex items-center justify-center'</span>&gt;
      &lt;Demo /&gt;
    &lt;/main&gt;
  );
}
</code></pre>
<p>Now the app looks like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706192781006/8d2f2e92-f3f6-4680-b0a4-4cbc988c8f71.png" alt class="image--center mx-auto" /></p>
<p>Clicking on it will do nothing as of now.</p>
<p>Now go to Demo.tsx and import cn function to it.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { cn } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/lib/utils'</span>;
</code></pre>
<p>Modify your button to below code.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
    <span class="hljs-attr">type</span>=<span class="hljs-string">'button'</span>
    <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setState(!state)}
    className={cn(
        'text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800',
        state &amp;&amp;
        'focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800'
        )}
&gt;
    Click me to change the color of me
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In the above code we added an onClick event to the button that negates the state value when clicked on it. we modified className to use cn function. The final code looks like this.</p>
<pre><code class="lang-typescript"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { cn } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/lib/utils'</span>;
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">interface</span> DemoProps {}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Demo = <span class="hljs-function">(<span class="hljs-params">{}: DemoProps</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [state, setState] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">return</span> (
    &lt;div className=<span class="hljs-string">'flex'</span>&gt;
      &lt;button
        <span class="hljs-keyword">type</span>=<span class="hljs-string">'button'</span>
        onClick={<span class="hljs-function">() =&gt;</span> setState(!state)}
        className={cn(
          !state &amp;&amp;
            <span class="hljs-string">'text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800'</span>,
          state &amp;&amp;
            <span class="hljs-string">'focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800'</span>
        )}
      &gt;
        Click me to change the color <span class="hljs-keyword">of</span> me
      &lt;/button&gt;
    &lt;/div&gt;
  );
};
</code></pre>
<p>The above code is a React component named Demo. It is a functional component that doesn't take any props. Let's break down the code step by step:</p>
<ol>
<li><p><strong>useState Hook</strong>: The component uses the <code>useState</code> hook from React to create a state variable <code>state</code> and a function <code>setState</code> to update this state. The initial value of <code>state</code> is <code>false</code>.</p>
</li>
<li><p><strong>JSX</strong>: Inside the <code>return</code> statement, the component returns JSX, which represents the UI. It consists of a <code>div</code> element with a class name of 'flex' and a <code>button</code> element.</p>
</li>
<li><p><strong>Button</strong>: The button has an <code>onClick</code> event handler that toggles the value of <code>state</code> when clicked. It also has a dynamic class name based on the value of <code>state</code>. The <code>cn</code> function is used to conditionally apply class names based on the value of <code>state</code>.</p>
</li>
<li><p><strong>Conditional Class Names</strong>: The <code>cn</code> function is used to conditionally apply class names to the button based on the value of <code>state</code>. When <code>state</code> is <code>false</code>, it applies a set of classes related to the blue color scheme, and when <code>state</code> is <code>true</code>, it applies a set of classes related to the green color scheme.</p>
</li>
<li><p><strong>Button Text</strong>: The button text says "Click me to change the color of me".</p>
</li>
</ol>
<p>In summary, this component renders a button that changes its color when clicked, toggling between blue and green, and the color change is reflected in the button's appearance based on the state value.</p>
<h2 id="heading-summary">Summary</h2>
<p>Using 'clsx' and 'tailwind merge' we can write conditional classes.</p>
]]></content:encoded></item><item><title><![CDATA[What is useRef hook and where to use it?]]></title><description><![CDATA[In React, the useRef hook is used to create a mutable reference that can be attached to a DOM element or any mutable value. This reference persists for the entire lifecycle of the component, and changing the reference does not trigger a re-render. Th...]]></description><link>https://bitstoqubits.hashnode.dev/what-is-useref-hook-and-where-to-use-it</link><guid isPermaLink="true">https://bitstoqubits.hashnode.dev/what-is-useref-hook-and-where-to-use-it</guid><category><![CDATA[React]]></category><category><![CDATA[hooks]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Satishkumar]]></dc:creator><pubDate>Wed, 27 Dec 2023 13:02:09 GMT</pubDate><content:encoded><![CDATA[<p>In React, the useRef hook is used to create a mutable reference that can be attached to a DOM element or any mutable value. This reference persists for the entire lifecycle of the component, and changing the reference does not trigger a re-render. This makes useRef useful for accessing the DOM directly within functional components, storing mutable values, and more.</p>
<p>Here's a detailed explanation with an example:</p>
<p><strong>Basic Syntax:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useRef } <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">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myRef = useRef(initialValue);
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p>We import the <code>useRef</code> hook from the 'react' package.</p>
</li>
<li><p>Inside the functional component <code>MyComponent</code>, we call <code>useRef</code> and pass an optional <code>initialValue</code> as an argument. This creates a mutable reference, initialized with the provided value.</p>
</li>
</ul>
<p><strong>Example:</strong> Let's consider an example where we use useRef to access and focus on an input field when the component mounts.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useRef, useEffect } <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">InputFocusExample</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    inputRef.current.focus();
  }, []);

  <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">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> inputRef.current.focus()}&gt;Focus Input<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>
  );
}
</code></pre>
<p><strong>Explanation of the Example:</strong></p>
<ol>
<li><p>We import the <code>useRef</code> and <code>useEffect</code> hooks from 'react'.</p>
</li>
<li><p>Inside the <code>InputFocusExample</code> component, we create a mutable reference <code>inputRef</code> using the <code>useRef</code> hook and initialize it with <code>null</code>.</p>
</li>
<li><p>We use the <code>useEffect</code> hook to focus on the input element when the component mounts. We do this by accessing the DOM element using <code>inputRef.current</code> and calling the <code>focus</code> method.</p>
</li>
<li><p>We return a JSX element that includes an input field with the <code>ref</code> attribute set to <code>inputRef</code>, and a button that, when clicked, also focuses on the input field using <code>inputRef.current.focus()</code>.</p>
</li>
</ol>
<p>In this example, we've used the useRef hook to access and interact with a DOM element directly within a functional component, demonstrating its practical use for managing DOM interactions.</p>
<h2 id="heading-use-cases-of-useref-hook">Use cases of useRef hook.</h2>
<p>Certainly! Let's go through each of the use cases of the useRef hook with examples:</p>
<ol>
<li><p><strong>Accessing DOM Elements:</strong> Use useRef to access and interact with DOM elements directly within functional components. This is useful for scenarios like focusing on an input field, measuring the size of an element, or integrating with third-party DOM libraries.</p>
<p> Example:</p>
<pre><code class="lang-jsx"> <span class="hljs-keyword">import</span> React, { useRef, useEffect } <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">MyComponent</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>);

   useEffect(<span class="hljs-function">() =&gt;</span> {
     inputRef.current.focus();
   }, []);

   <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span></span>;
 }
</code></pre>
</li>
<li><p><strong>Storing Previous Values:</strong> useRef can be used to store values that need to persist across re-renders without causing a re-render when the value changes. This is useful for storing previous values, such as the previous state or props, for comparison in subsequent renders.</p>
<p> Example:</p>
<pre><code class="lang-jsx"> <span class="hljs-keyword">import</span> React, { useRef, useEffect } <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">MyComponent</span>(<span class="hljs-params">{ value }</span>) </span>{
   <span class="hljs-keyword">const</span> previousValueRef = useRef();

   useEffect(<span class="hljs-function">() =&gt;</span> {
     previousValueRef.current = value;
   }, [value]);

   <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Previous value: {previousValueRef.current}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
 }
</code></pre>
</li>
<li><p><strong>Caching Values:</strong> You can use useRef to cache values that need to persist for the entire lifecycle of the component, without causing re-renders when the value changes. This is useful for storing values that are expensive to compute.</p>
<p> Example:</p>
<pre><code class="lang-jsx"> <span class="hljs-keyword">import</span> React, { useRef, useEffect } <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">MyComponent</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> dataCache = useRef(<span class="hljs-literal">null</span>);

   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (!dataCache.current) {
       dataCache.current = fetchData(); <span class="hljs-comment">// Expensive operation</span>
     }
     <span class="hljs-comment">// Use dataCache.current</span>
   }, []);

   <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Data: {dataCache.current}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
 }
</code></pre>
</li>
<li><p><strong>Storing Mutable Values:</strong> useRef can store mutable values that do not trigger a re-render when they are changed. This is useful for managing values that need to persist across re-renders but don't need to trigger a component update.</p>
<p> Example:</p>
<pre><code class="lang-jsx"> <span class="hljs-keyword">import</span> React, { useRef, useState } <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">MyComponent</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> renderCount = useRef(<span class="hljs-number">0</span>);
   <span class="hljs-keyword">const</span> [state, setState] = useState(<span class="hljs-number">0</span>);

   renderCount.current++;

   <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">div</span>&gt;</span>Render count: {renderCount.current}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setState(state + 1)}&gt;Update State<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>
   );
 }
</code></pre>
</li>
<li><p><strong>Referencing Unchanging Values:</strong> Use useRef to reference values that do not change over time, such as event handlers or other callback functions, to avoid unnecessary re-renders.</p>
<p> Example:</p>
<pre><code class="lang-jsx"> <span class="hljs-keyword">import</span> React, { useRef } <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">MyComponent</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> clickHandler = useRef(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked'</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">{clickHandler.current}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
 }
</code></pre>
</li>
</ol>
<p>These examples demonstrate the various use cases of the useRef hook in React, showcasing its versatility in managing state, optimizing performance, and interacting with the DOM.</p>
]]></content:encoded></item><item><title><![CDATA[useEffect vs useLayoutEffect]]></title><description><![CDATA[Hooks
In React, hooks are functions that allow functional components to "hook into" React state and lifecycle features. They enable you to use state and other React features without writing a class. Hooks were introduced in React 16.8 to address comp...]]></description><link>https://bitstoqubits.hashnode.dev/useeffect-vs-uselayouteffect</link><guid isPermaLink="true">https://bitstoqubits.hashnode.dev/useeffect-vs-uselayouteffect</guid><category><![CDATA[React]]></category><category><![CDATA[ReactHooks]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[react hooks]]></category><dc:creator><![CDATA[Satishkumar]]></dc:creator><pubDate>Mon, 25 Dec 2023 11:00:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703501859927/143879fb-b20d-4c88-b503-1bea16bef036.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-hooks">Hooks</h2>
<p>In React, hooks are functions that allow functional components to "hook into" React state and lifecycle features. They enable you to use state and other React features without writing a class. Hooks were introduced in React 16.8 to address complex scenarios like state management, side effects, and context usage in functional components.</p>
<p>The most commonly used hooks include useState for managing state, useEffect for handling side effects, useContext for accessing context, and useReducer for more complex state management. These hooks provide a more concise and readable way to work with React components, promoting reusability and composability.</p>
<p>By using hooks, developers can write more modular and maintainable code, making it easier to share logic across multiple components. This approach also aligns with the functional programming paradigm, allowing for better separation of concerns and improved code organization.</p>
<h2 id="heading-what-is-useeffect">What is useEffect?</h2>
<p>The useEffect is a hook in React, which allows you to perform side effects in function components. Side effects may include data fetching, subscriptions, or manually changing the DOM in React components.</p>
<p>When you use the useEffect hook, you are telling React that your component needs to do something after it renders. React will remember the function you passed and call it after performing the DOM updates.</p>
<p>The useEffect hook takes two arguments: a function and an optional array of dependencies. The function passed to useEffect is the actual effect you want to perform, and it can optionally return a cleanup function. The second argument, the array of dependencies, is used to specify what values the effect depends on. If any of the values in the dependencies array change, the effect function will be re-executed.</p>
<ol>
<li><p><strong>Data Fetching</strong>: You can use the useEffect hook to fetch data from an API when a component mounts. For example:</p>
<pre><code class="lang-javascript"> useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
         <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://api.example.com/data'</span>);
         setData(result.data);
     };
     fetchData();
 }, []);
</code></pre>
</li>
<li><p><strong>Subscriptions</strong>: If your component needs to subscribe to some external event source, you can use the useEffect hook to set up and clean up the subscription. For example:</p>
<pre><code class="lang-javascript"> useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> subscription = eventSource.subscribe(<span class="hljs-string">'event'</span>, <span class="hljs-function"><span class="hljs-params">eventData</span> =&gt;</span> {
         <span class="hljs-comment">// Handle event data</span>
     });
     <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
         subscription.unsubscribe();
     };
 }, []);
</code></pre>
</li>
<li><p><strong>Document Title Update</strong>: You can use the useEffect hook to update the document title based on the state of the component.</p>
<pre><code class="lang-javascript"> useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-built_in">document</span>.title = <span class="hljs-string">`You clicked <span class="hljs-subst">${count}</span> times`</span>;
 }, [count]);
</code></pre>
</li>
<li><p><strong>Cleanup</strong>: If your effect needs to clean up after itself, you can return a function from the effect. This function will be called when the component unmounts or when the dependencies change.</p>
<pre><code class="lang-javascript"> useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> subscription = someStream.subscribe();
     <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
         subscription.unsubscribe();
     };
 }, [someStream]);
</code></pre>
</li>
</ol>
<p>These are just a few examples of how the useEffect hook can be used in React to handle various side effects in function components. It's a powerful tool for managing side effects and keeping your components clean and efficient.</p>
<h2 id="heading-what-is-uselayouteffect">What is useLayoutEffect?</h2>
<p>The useLayoutEffect is a hook in React that is very similar to the useEffect hook. The primary difference is when it is executed in relation to the render phase.</p>
<p>While the useEffect hook runs after the render is committed to the screen, the useLayoutEffect hook runs synchronously immediately after the DOM has been updated but before the browser has had a chance to paint those changes on the screen. This makes it suitable for operations that need to be performed synchronously and may affect the layout of the page.</p>
<p>The signature of useLayoutEffect is the same as useEffect, taking a function as the first argument and an optional array of dependencies as the second argument. The function passed to useLayoutEffect will be executed synchronously after the DOM has been updated.</p>
<p>It's important to note that while useLayoutEffect can be more performant in certain cases, it can also block the browser's painting process if not used carefully. Therefore, it should be used with caution and only when the synchronous nature of the effect is necessary.</p>
<ol>
<li><p><strong>Measuring DOM Elements</strong>: If you need to measure the size or position of a DOM element and use that information synchronously, you can use useLayoutEffect. For example:</p>
<pre><code class="lang-javascript"> useLayoutEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> { width, height } = someDOMElement.getBoundingClientRect();
     <span class="hljs-comment">// Use the width and height synchronously</span>
 }, [someDependency]);
</code></pre>
</li>
<li><p><strong>Synchronous DOM Manipulation</strong>: If you need to perform synchronous DOM manipulations that affect the layout, you can use useLayoutEffect. For example:</p>
<pre><code class="lang-javascript"> useLayoutEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-comment">// Perform synchronous DOM manipulations</span>
 }, [someDependency]);
</code></pre>
</li>
<li><p><strong>Scroll Position Restoration</strong>: If you need to restore the scroll position of a container after a re-render, you can use useLayoutEffect to ensure that the scroll position is restored synchronously.</p>
<pre><code class="lang-javascript"> useLayoutEffect(<span class="hljs-function">() =&gt;</span> {
     containerRef.current.scrollTop = savedScrollPosition;
 }, [savedScrollPosition]);
</code></pre>
</li>
<li><p><strong>Synchronous State Updates</strong>: If you need to perform state updates that affect the layout synchronously, you can use useLayoutEffect. For example:</p>
<pre><code class="lang-javascript"> useLayoutEffect(<span class="hljs-function">() =&gt;</span> {
     setDimensions(calculateDimensions());
 }, [someDependency]);
</code></pre>
</li>
</ol>
<p>These are just a few examples of how the useLayoutEffect hook can be used in React to handle synchronous operations that may affect the layout of the page. It's important to use useLayoutEffect judiciously, as it can impact performance and should only be used when synchronous layout-affecting operations are necessary.</p>
<h2 id="heading-useeffect-vs-uselayouteffect">useEffect vs useLayoutEffect</h2>
<p>The primary difference between useEffect and useLayoutEffect lies in when they are executed in relation to the render phase.</p>
<ol>
<li><p><strong>useEffect</strong>:</p>
<ul>
<li><p>Runs asynchronously after the render is committed to the screen.</p>
</li>
<li><p>It does not block the browser from updating the screen, making it suitable for most side effects that do not require immediate synchronous updates to the DOM.</p>
</li>
<li><p>Use useEffect for data fetching, subscriptions, or other side effects that do not need to be performed synchronously and do not affect the layout of the page.</p>
</li>
</ul>
</li>
<li><p><strong>useLayoutEffect</strong>:</p>
<ul>
<li><p>Runs synchronously immediately after the DOM has been updated but before the browser has had a chance to paint those changes on the screen.</p>
</li>
<li><p>It can block the browser's painting process if not used carefully, so it should be used with caution.</p>
</li>
<li><p>Use useLayoutEffect when you need to perform synchronous operations that may affect the layout of the page, such as measuring DOM elements, performing synchronous DOM manipulations, restoring scroll positions, or performing synchronous state updates.</p>
</li>
</ul>
</li>
</ol>
<p>In summary, useEffect is suitable for most side effects that do not require immediate synchronous updates to the DOM, while useLayoutEffect is used for synchronous operations that may affect the layout of the page and need to be performed immediately after the DOM has been updated. It's important to choose the appropriate hook based on the timing and nature of the side effect you want to perform.</p>
<h2 id="heading-when-to-use-useeffect-and-when-to-use-uselayouteffect">When to use useEffect and when to use useLayoutEffect?</h2>
<p>You should use useEffect when you need to perform side effects that do not require immediate synchronous updates to the DOM. This includes data fetching, subscriptions, or other side effects that do not need to be performed synchronously and do not affect the layout of the page.</p>
<p>On the other hand, you should use useLayoutEffect when you need to perform synchronous operations that may affect the layout of the page and need to be executed immediately after the DOM has been updated. This includes tasks such as measuring DOM elements, performing synchronous DOM manipulations, restoring scroll positions, or performing synchronous state updates.</p>
<p>In general, if your side effect does not require immediate synchronous updates to the DOM, and it does not affect the layout of the page, you should use useEffect. If your side effect requires immediate synchronous updates to the DOM and may affect the layout of the page, then use useLayoutEffect.</p>
<p>It's important to consider the timing and nature of the side effect you want to perform when choosing between useEffect and useLayoutEffect to ensure that the side effect is executed at the appropriate phase of the component lifecycle.  </p>
<p>Helpful links:<br /><a target="_blank" href="https://www.youtube.com/watch?v=wU57kvYOxT4">https://www.youtube.com/watch?v=wU57kvYOxT4</a> (simple explanation)</p>
]]></content:encoded></item><item><title><![CDATA[What are Microservices? - Explained for newbies.]]></title><description><![CDATA[Understanding the problem with an example.
Let's assume that you are going to build a physical teaching space for around 30 students. How will you execute this task? You will first start by maintaining a ledger to document the details of the students...]]></description><link>https://bitstoqubits.hashnode.dev/what-are-microservices-explained-for-newbies</link><guid isPermaLink="true">https://bitstoqubits.hashnode.dev/what-are-microservices-explained-for-newbies</guid><category><![CDATA[software development]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[monolithic architecture]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Satishkumar]]></dc:creator><pubDate>Thu, 14 Dec 2023 02:23:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702521467313/618bdcc2-9577-43f3-8f34-88fd14195abb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-understanding-the-problem-with-an-example">Understanding the problem with an example.</h2>
<p>Let's assume that you are going to build a physical teaching space for around 30 students. How will you execute this task? You will first start by maintaining a ledger to document the details of the students. There may be different types of ledgers based on various requirements. For example, you may use different ledgers for admitting the students and then for maintaining their academic performance. As of now, you can handle 30 students and their admission process as well as academic-related work. Coming to physical resources, you have rented a decent-sized room.</p>
<p>The current size of the teaching space:</p>
<ul>
<li><p>Students: 30</p>
</li>
<li><p>Services: Admission, Teaching</p>
</li>
<li><p>Faculty: 1</p>
</li>
<li><p>Rooms: 1</p>
</li>
</ul>
<p>With time, thanks to your teaching skills, you started receiving admission requests from 100 students. You don't want to miss the opportunity of growing your new hustle. So now you have to scale up your teaching space to accommodate these extra students. You alone can't handle all the tasks of teaching and administration work, so you start hiring employees to manage the other required tasks. Now you have two people to handle the admission process and to teach students. You rent another room to accommodate the extra students.</p>
<p>The current size of the teaching space:</p>
<ul>
<li><p>Students: 130</p>
</li>
<li><p>Services: Admission, Teaching</p>
</li>
<li><p>Faculty: 3</p>
</li>
<li><p>Rooms: 2</p>
</li>
</ul>
<p>Let's say for the next episode of admissions, you get a request from 1000 students. Now it becomes quite difficult for the current system to handle this many students. The idea of one faculty member handling multiple tasks can become quite an obstacle when building a teaching space for a large number of students. This idea of building an application or designing a system is called a Monolithic model.</p>
<p>In software engineering, a monolithic application is a single unified software application that is self-contained and independent from other applications but typically lacks flexibility. There are advantages and disadvantages of building applications in a monolithic style of software architecture, depending on the requirements. You can see how difficult it can become to handle a huge number of people. The solution that engineers came up with for this problem is Microservices architecture.</p>
<p>Now you can build a large-scale teaching space as big as a university using this Microservices concept. In a university, there are separate departments providing different services for the university. Each department is independent from each other. They can use services provided by other departments but are independent in terms of scaling up and down.</p>
<p>Departments and their services:</p>
<ul>
<li><p>Admission Department: Admitting students, verifying students, and authorizing them (ID cards).</p>
</li>
<li><p>Accounts Department: Handling the fees and other money-related tasks.</p>
</li>
<li><p>Security Department: Provides physical security to the university.</p>
</li>
<li><p>Administration Department: Handles administrative work.</p>
</li>
<li><p>Computer Science Department: Uses services provided by the Admission department to check whether a student is authorized to attend classes. The department has internal independent services that it uses to run the department, such as teaching, etc.</p>
</li>
</ul>
<p>Using this approach, you can add other departments/services and also scale up each department to handle as many people as required.</p>
<h2 id="heading-monolithic-architecture">Monolithic architecture</h2>
<p>In a monolithic architecture, all the components of an application are interconnected and interdependent. This means that the entire application is built as a single unit, including the user interface, server-side processing, and data access.</p>
<p>If we were to use Instagram as an example of a monolithic architecture, the server would handle various routes for different functionalities of the application. For instance, the server would handle routes for user authentication, profile management, image uploading, feed generation, and interactions such as likes and comments.</p>
<p>Here are some example routes that the server in a monolithic Instagram architecture might handle:</p>
<ol>
<li><p>User authentication:</p>
<ul>
<li>Route: /login, /logout, /signup</li>
</ul>
</li>
<li><p>Profile management:</p>
<ul>
<li>Route: /profile, /edit-profile, /change-password</li>
</ul>
</li>
<li><p>Image uploading:</p>
<ul>
<li>Route: /upload-image, /delete-image, /edit-image</li>
</ul>
</li>
<li><p>Feed generation:</p>
<ul>
<li>Route: /feed, /explore, /search</li>
</ul>
</li>
<li><p>Interactions (likes, comments):</p>
<ul>
<li>Route: /like, /unlike, /comment, /delete-comment</li>
</ul>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702518812916/783ace16-b8bb-4be5-852f-e8eeba98b670.png" alt class="image--center mx-auto" /></p>
<p>In a monolithic architecture, all these routes would be handled within the same codebase and deployed as a single unit. This architecture can make it easier to develop and test the application as a whole, but it can also lead to challenges in scalability and maintenance as the application grows.</p>
<h2 id="heading-microservices-architecture">Microservices architecture</h2>
<p>In a microservices architecture, the application is broken down into a collection of loosely coupled services, each responsible for a specific set of functionalities. Using Instagram as an example, the various functionalities of the application would be divided into separate microservices, each with its codebase and database.</p>
<p>In the context of Instagram, the microservices architecture might be structured as follows:</p>
<ol>
<li><p>User service:</p>
<ul>
<li><p>Responsible for user authentication, profile management, and user-related functionalities.</p>
</li>
<li><p>Routes: /login, /logout, /signup, /profile, /edit-profile, /change-password</p>
</li>
</ul>
</li>
<li><p>Image service:</p>
<ul>
<li><p>Handles image uploading, editing, and deletion.</p>
</li>
<li><p>Routes: /upload-image, /delete-image, /edit-image</p>
</li>
</ul>
</li>
<li><p>Feed service:</p>
<ul>
<li><p>Generates user feeds, and handles explore and search functionalities.</p>
</li>
<li><p>Routes: /feed, /explore, /search</p>
</li>
</ul>
</li>
<li><p>Interaction service:</p>
<ul>
<li><p>Manages user interactions such as likes, comments, and notifications.</p>
</li>
<li><p>Routes: /like, /unlike, /comment, /delete-comment</p>
</li>
</ul>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702519721483/ce966dfb-849f-45f1-b2d2-069602cea40b.png" alt class="image--center mx-auto" /></p>
<p>Each of these services would have its own database and can be developed, deployed, and scaled independently. This architecture allows for greater flexibility, scalability, and resilience. However, it also introduces complexities in terms of inter-service communication, data consistency, and deployment orchestration.</p>
<p>In a microservices architecture, the focus is on creating small, focused services that can be developed and maintained by small, autonomous teams. This approach can lead to better scalability, fault isolation, and the ability to use different technologies for different services. However, it also requires careful design and management of inter-service communication and data consistency.</p>
<h2 id="heading-advantages-vs-disadvantages">Advantages vs Disadvantages</h2>
<p>Advantages of Monolithic Architecture:</p>
<ol>
<li><p>Simplicity: Easier to develop, test, and deploy as the entire application is contained within a single codebase.</p>
</li>
<li><p>Performance: Lower latency as there is no inter-service communication overhead.</p>
</li>
<li><p>Debugging: Easier to debug and trace issues as the entire application is in one codebase.</p>
</li>
<li><p>Development Environment: Simplicity in setting up the development environment as there is only one application to run.</p>
</li>
</ol>
<p>Disadvantages of Monolithic Architecture:</p>
<ol>
<li><p>Scalability: Difficult to scale specific modules independently, which can lead to over-provisioning.</p>
</li>
<li><p>Technology Stack: Limited flexibility in choosing different technologies for different modules.</p>
</li>
<li><p>Maintenance: Changes to one part of the application may require redeployment of the entire application.</p>
</li>
<li><p>Team Collaboration: Larger teams may find it challenging to work on the same codebase without conflicts.</p>
</li>
</ol>
<p>Advantages of Microservices Architecture:</p>
<ol>
<li><p>Scalability: Each service can be scaled independently based on its specific needs.</p>
</li>
<li><p>Flexibility: Different services can use different technologies, allowing for flexibility in choosing the right tool for the job.</p>
</li>
<li><p>Fault Isolation: Failures in one service do not necessarily affect the entire application.</p>
</li>
<li><p>Team Autonomy: Small, autonomous teams can work on individual services, leading to faster development and deployment.</p>
</li>
</ol>
<p>Disadvantages of Microservices Architecture:</p>
<ol>
<li><p>Complexity: Introduces complexities in inter-service communication, data consistency, and deployment orchestration.</p>
</li>
<li><p>Testing: End-to-end testing becomes more complex due to the distributed nature of the application.</p>
</li>
<li><p>Operational Overhead: Requires additional effort to manage and monitor multiple services.</p>
</li>
<li><p>Latency: Inter-service communication can introduce latency compared to monolithic architecture.</p>
</li>
</ol>
<p>It's important to carefully consider these factors and the specific requirements of the application when choosing between monolithic and microservices architectures. Each has its own set of trade-offs, and the decision should be based on a thorough analysis of the application's needs and the team's capabilities.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, both monolithic and microservices architectures have their advantages and challenges. The monolithic architecture offers simplicity in development and testing, but it can become complex and challenging to scale as the application grows. On the other hand, the microservices architecture provides flexibility, scalability, and fault isolation, but it introduces complexities in terms of inter-service communication and data consistency.</p>
<p>When choosing between these architectures, it's important to consider the specific needs of the application, the development team's expertise, and the long-term scalability requirements. Both architectures have been successfully used by various applications, including Instagram, and the decision should be based on a thorough analysis of the trade-offs involved.</p>
<h3 id="heading-some-useful-links">Some useful links:</h3>
<p><a target="_blank" href="https://www.spiceworks.com/tech/devops/articles/what-are-microservices/">https://www.spiceworks.com/tech/devops/articles/what-are-microservices/</a></p>
<p><a target="_blank" href="https://www.openlegacy.com/blog/microservices-architecture-patterns/">https://www.openlegacy.com/blog/microservices-architecture-patterns/</a></p>
]]></content:encoded></item><item><title><![CDATA[What is ShadcnUI? and how you can use it to improve your UI development experience?]]></title><description><![CDATA[What are UI libraries?
UI libraries, also known as User Interface libraries, are collections of pre-designed and pre-built components, styles, and functionalities that developers can use to create user interfaces for their applications. These librari...]]></description><link>https://bitstoqubits.hashnode.dev/what-is-shadcnui-and-how-you-can-use-it-to-improve-your-ui-development-experience</link><guid isPermaLink="true">https://bitstoqubits.hashnode.dev/what-is-shadcnui-and-how-you-can-use-it-to-improve-your-ui-development-experience</guid><category><![CDATA[Next.js]]></category><category><![CDATA[shadcn ui]]></category><category><![CDATA[shadcn]]></category><dc:creator><![CDATA[Satishkumar]]></dc:creator><pubDate>Thu, 12 Oct 2023 16:12:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703504157945/a1510e78-388b-4b14-8b0a-f18e563b2657.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-are-ui-libraries">What are UI libraries?</h3>
<p>UI libraries, also known as User Interface libraries, are collections of pre-designed and pre-built components, styles, and functionalities that developers can use to create user interfaces for their applications. These libraries provide a set of reusable UI elements, such as buttons, forms, menus, and cards, that follow consistent design patterns and guidelines.</p>
<p>By using UI libraries, developers can save time and effort by leveraging pre-built components instead of creating them from scratch. These libraries often come with customizable options, allowing developers to tailor the UI components to match their application's specific design requirements.</p>
<p>UI libraries are commonly used in web development, where they are implemented using HTML, CSS, and JavaScript. They provide a foundation for building visually appealing and user-friendly interfaces, enabling developers to focus more on the application's logic and functionality.</p>
<p>Some popular UI libraries for React include Material-UI, Chakra UI, Ant Design, and Tailwind CSS. These libraries offer a wide range of components and styles that can be easily integrated into React applications, making the development process more efficient and consistent.</p>
<h3 id="heading-what-is-shadcnui">What is ShadcnUI?</h3>
<p>"<a target="_blank" href="https://ui.shadcn.com/">Shadcn UI</a> <strong>is NOT</strong> a component library. It's a collection of reusable components that you can copy and paste into your apps." This is what you see when you open the docs of ShadcnUI.</p>
<p>To gain a better understanding of the statement, let's compare MUI with shadcnUI. When utilizing MUI's components, it is necessary to install the required dependencies and directly import the components from those dependencies. However, this approach has a drawback: it limits our control over the components used to construct our application. Developers are unable to modify the styling or customize the components to suit their specific requirements.</p>
<p>ShadcnUI, on the other hand, addresses this issue by offering components that can be easily modified, styled, and utilized based on individual needs. Now, you might wonder how shadcnUI accomplishes this.</p>
<h3 id="heading-exploring-shadcnui">Exploring ShadcnUI.</h3>
<p>Shadcn offers the advantage of installing only the required components when needed, eliminating the need to install all components at once. Whether you need a button component or an input component for your app, you can simply install them individually. The process of installing these components is as easy as running a command in your Terminal.</p>
<p>Let's say that you are building a React app using Next.js. Let's assume that you have already installed Next.js. Once Next.js is installed, you can proceed with initializing ShadcnUI. To do this, open your terminal and navigate to the root directory of your Next.js project. Then, run the following command:</p>
<pre><code class="lang-powershell">npx shadcn<span class="hljs-literal">-ui</span>@latest init
</code></pre>
<p>This command will initialize ShadcnUI in your project and guide you through the configuration process. You'll be prompted with options to customize the installation according to your needs.</p>
<p>You will be asked a few questions to configure <code>components.json</code></p>
<pre><code class="lang-plaintext">Would you like to use TypeScript (recommended)? no / yes
Which style would you like to use? › Default
Which color would you like to use as base color? › Slate
Where is your global CSS file? › › app/globals.css
Do you want to use CSS variables for colors? › no / yes
Where is your tailwind.config.js located? › tailwind.config.js
Configure the import alias for components: › @/components
Configure the import alias for utils: › @/lib/utils
Are you using React Server Components? › no / yes
</code></pre>
<p>For a more detailed installation guide specific to Next.js apps, you can refer to the official ShadcnUI documentation or visit their website.</p>
<p>Here's a recommended folder structure for Next.js apps. You can use this as a reference:</p>
<pre><code class="lang-plaintext">.
├── app
│   ├── layout.tsx
│   └── page.tsx
├── components
│   ├── ui
│   │   ├── alert-dialog.tsx
│   │   ├── button.tsx
│   │   ├── dropdown-menu.tsx
│   │   └── ...
│   ├── main-nav.tsx
│   ├── page-header.tsx
│   └── ...
├── lib
│   └── utils.ts
├── styles
│   └── globals.css
├── next.config.js
├── package.json
├── postcss.config.js
├── tailwind.config.js
└── tsconfig.json
</code></pre>
<p>When you install the components, they will be added to the <code>components/ui</code> folder. In the example folder structure above, you can see three components already included: <code>alert-dialog.tsx</code>, <code>button.tsx</code>, and <code>dropdown-menu.tsx</code>. These components serve as examples and can be modified to suit your specific requirements. Once customized, you can import them into any part of your application as needed.</p>
<h3 id="heading-adding-components-to-your-nextjs-app">Adding components to your Next.js app.</h3>
<p>To add the Button component to your app, follow these simple steps:</p>
<ol>
<li><p>Visit the <a target="_blank" href="https://ui.shadcn.com/docs">ShadcnUI</a> documentation website.</p>
</li>
<li><p>Navigate to the components section of the documentation.</p>
</li>
<li><p>Locate the <a target="_blank" href="https://ui.shadcn.com/docs/components/button">Button</a> component and copy the command provided.</p>
</li>
<li><p>Open the root directory of your project.</p>
</li>
<li><p>Paste the copied command into your terminal or command prompt.</p>
<p> <code>npx shadcn-ui@latest add button</code></p>
</li>
<li><p>Run the command to add the latest version of the ShadcnUI Button component to your project.</p>
</li>
</ol>
<p>Once the Button component is successfully added, you can easily incorporate it into any part of your application. This streamlined process ensures a seamless integration of the Button component into your project, saving you time and effort.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codesandbox.io/p/sandbox/condescending-poitras-dsggds?file=%2Fapp%2Flayout.tsx%3A1%2C1">https://codesandbox.io/p/sandbox/condescending-poitras-dsggds?file=%2Fapp%2Flayout.tsx%3A1%2C1</a></div>
<p> </p>
<p>I have prepared a CodeSandbox for you to practice ShadcnUI. Please take some time to explore and familiarize yourself with its features. This hands-on experience will help you gain proficiency in utilizing ShadcnUI effectively.</p>
]]></content:encoded></item><item><title><![CDATA[I want to build a really cool planner App.]]></title><description><![CDATA[Introduction
I am interested in developing a planner application that incorporates additional features to greatly enhance daily life. While I am aware of the existence of apps similar to Notion, I find Notion to be overly intricate for my preferences...]]></description><link>https://bitstoqubits.hashnode.dev/i-want-to-build-a-really-cool-planner-app</link><guid isPermaLink="true">https://bitstoqubits.hashnode.dev/i-want-to-build-a-really-cool-planner-app</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Planner]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[projects]]></category><dc:creator><![CDATA[Satishkumar]]></dc:creator><pubDate>Tue, 08 Aug 2023 23:13:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cckf4TsHAuw/upload/03954385d6332e10fbddd2b3df6ff194.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h1 id="heading-introduction">Introduction</h1>
<p>I am interested in developing a planner application that incorporates additional features to greatly enhance daily life. While I am aware of the existence of apps similar to Notion, I find Notion to be overly intricate for my preferences. My goal is to create an app that exudes simplicity, productivity, and a sense of coolness. It is imperative that users can effortlessly comprehend the app's functionality and features, enabling them to maximize its potential and derive significant benefits from its usage.</p>
<p>I will regularly update my blog with the latest developments on the app, providing insights into the technologies I will be utilizing and the resources I will be leveraging to acquire knowledge in those areas. As I am relatively new to blogging, there may be instances where the user experience may not be optimal while navigating through my content. I apologize in advance for any inconvenience this may cause.</p>
<h1 id="heading-the-vision-creating-a-simple-yet-productive-app">The Vision: Creating a simple yet productive App</h1>
<p>The application is an enhanced version of a TO-DO app, designed to seamlessly integrate into users' daily lives. My goal is for this app to become the go-to choice for individuals seeking productivity tools. Looking ahead, I envision incorporating artificial intelligence to enhance the application's features. Currently, the final product will include robust task scheduling capabilities, allowing users to prioritize tasks and schedule them using calendars. Additionally, users will have the ability to create weekly or monthly timetables, take notes, and easily share them through links. Furthermore, I am considering implementing real-time collaboration for note-taking, enabling users to collaborate in real time. Lastly, users will be able to schedule meetings using popular platforms such as Google Meet or Zoom.</p>
<h1 id="heading-some-stand-out-features">Some stand-out features.</h1>
<h2 id="heading-real-time-collaboration">Real-time collaboration.</h2>
<p>I envision the application to incorporate a real-time collaboration feature for note-taking purposes. This functionality would enable a group of users to seamlessly contribute to tasks simultaneously, allowing for the addition of various content types such as text, images, and more. The inclusion of this feature would undoubtedly enhance the effectiveness of note-taking, providing users with a valuable tool for collaborative and efficient information capture.</p>
<h2 id="heading-an-ai-powered-chat-system">An ai powered chat system.</h2>
<p>Integrating an AI-powered chat system would be a valuable enhancement for the application. To illustrate the benefits, let's consider a scenario: Imagine you are utilizing this app and engaging in a conversation with another user or a group through the built-in chat system. While discussing various topics, you encounter a question or uncertainty that requires clarification. In such instances, having the ability to directly consult an AI would not only expedite the learning process but also add an element of enjoyment to the experience. By incorporating an AI-powered chat system, users can seamlessly seek assistance and gain valuable insights, thereby enhancing the overall functionality and user satisfaction of the application.</p>
<h1 id="heading-final-thoughts">Final thoughts</h1>
<p>The concepts are still vivid in my mind, and it is imperative that I meticulously outline the application in a more structured manner. It is crucial to ensure scalability, enabling seamless integration of new features as the project evolves. In my upcoming post, I will delve into the technology stack I am contemplating, followed by a comprehensive discussion of the app's design.</p>
]]></content:encoded></item></channel></rss>