<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Abhirup Datta</title>
    <description>The latest articles on DEV Community by Abhirup Datta (@abhidatta0).</description>
    <link>https://dev.to/abhidatta0</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F695339%2F6832ecc0-fcb9-4514-9d08-764f478da2b7.jpeg</url>
      <title>DEV Community: Abhirup Datta</title>
      <link>https://dev.to/abhidatta0</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/abhidatta0"/>
    <language>en</language>
    <item>
      <title>Manage Cart State with Zustand</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Wed, 05 Mar 2025 16:03:33 +0000</pubDate>
      <link>https://dev.to/abhidatta0/manage-cart-state-with-zustand-3f7d</link>
      <guid>https://dev.to/abhidatta0/manage-cart-state-with-zustand-3f7d</guid>
      <description>&lt;p&gt;Zustand, meaning “state” in German, is a lightweight state management library for React that offers an intuitive and efficient way to manage application state.&lt;/p&gt;

&lt;p&gt;In this blog, I will setup a simple cart application in Zustand .&lt;br&gt;
In Zustand, we store the state in a hook rather than a context (used in React-redux).&lt;/p&gt;

&lt;p&gt;Let's see the code 😄 &lt;br&gt;
Note: I have used TailwindCSS for styling the UI.&lt;/p&gt;

&lt;p&gt;After finishing, this is we will get this:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9dd3mre8yjdq9kb26ydd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9dd3mre8yjdq9kb26ydd.png" alt="Output" width="800" height="320"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;App.tsx&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Example static food items
import FoodItems from './FoodItems';
import ShoppingCart from './ShoppingCart';
import {Food} from './types';

const foodItems:Food[] = [
  {
    id: 1,
    name: "Burger",
    description: "Juicy grilled beef burger with fresh veggies",
    price: 5.99,
    image: "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?q=80&amp;amp;w=2799&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;ixlib=rb-4.0.3&amp;amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  },
  {
    id: 2,
    name: "Pizza",
    description: "Cheesy pizza topped with fresh tomatoes and basil",
    price: 8.99,
    image: "https://images.unsplash.com/photo-1513104890138-7c749659a591?q=80&amp;amp;w=2940&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;ixlib=rb-4.0.3&amp;amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  },
  {
    id: 3,
    name: "Salad",
    description: "Fresh mixed greens with a tangy vinaigrette",
    price: 4.99,
    image: "https://plus.unsplash.com/premium_photo-1701699257759-4189d01f4351?q=80&amp;amp;w=2787&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;ixlib=rb-4.0.3&amp;amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  },
  {
    id: 4,
    name: "Pasta",
    description: "Creamy Alfredo pasta with grilled chicken",
    price: 7.99,
    image: "https://images.unsplash.com/photo-1621996346565-e3dbc646d9a9?q=80&amp;amp;w=2706&amp;amp;auto=format&amp;amp;fit=crop&amp;amp;ixlib=rb-4.0.3&amp;amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
  },
];
const App = ()=&amp;gt; {

  return (
    &amp;lt;div className="flex"&amp;gt;
        &amp;lt;ShoppingCart /&amp;gt;
        &amp;lt;FoodItems items={foodItems}/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default App;

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

&lt;/div&gt;



&lt;p&gt;Here, I have added some sample food items. This is passed as props to  &lt;code&gt;FoodItems&lt;/code&gt;.We will see how to add the items from FoodItems to ShoppingCart "magically" via Zustand.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;cartStore.ts&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Food } from '@/types';
import {create} from 'zustand';

type Sku = {
    item: Food,
    count: number,
}
type CartStoreState = { 
    cart: Sku[],
    addToCart: (food: Food)=&amp;gt; void,
    incrementDecrementSku: (foodId: number, type: 'increment'|'decrement', quantity?: number )=&amp;gt; void,
    deleteSku: (foodId: number )=&amp;gt; void,
    clearCart: ()=&amp;gt; void,
}


export const useCartStore = create&amp;lt;CartStoreState&amp;gt;((set)=&amp;gt;({
    cart: [],
    addToCart: (product)=&amp;gt; set((state)=&amp;gt; {
        const cart = state.cart;
        const isSameProductExists = cart.find(sku =&amp;gt; sku.item.id === product.id);
        if(isSameProductExists){
            isSameProductExists.count += 1;
            return {cart:[...cart]};
        }
        return {cart: [...state.cart, {item: product, count: 1}] }
    }) ,
    incrementDecrementSku:(productId,  type, quantity = 1)=&amp;gt; set(state=&amp;gt; {
        const cart = state.cart;
        const productIndex = cart.findIndex(sku =&amp;gt; sku.item.id === productId);
        if(productIndex !== -1){
            const updatedCart = [...cart];
            const currentSku = updatedCart[productIndex];

            if(type === 'decrement'){
                if(currentSku.count &amp;lt;= quantity){
                   updatedCart.splice(productIndex,1); // Remove the product if count reaches 0 or below
                }else{
                    currentSku.count -= quantity;
                }
            }else if(type === 'increment'){
                currentSku.count += quantity;
            }
            return {cart:updatedCart};
        }
        return {cart: cart }
    }),
    deleteSku:(id)=&amp;gt; set((state)=&amp;gt; ({cart: state.cart.filter(sku=&amp;gt; sku.item.id !== id)})),
    clearCart:()=&amp;gt; set({cart: []})
}));

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;create&lt;/code&gt; function from zustand helps in creating a store .It takes a callback function with the first param which is a setter method 'set' and returns the state.&lt;br&gt;
Here, the state has five items: cart, addToCart, incrementDecrementSku,deleteSku , clearCart .&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;FoodItems.tsx&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useCartStore } from './store/cartStore';
import {Food} from './types';
import { Plus } from "lucide-react";

const FoodItems = ({ items }:{items: Food[]}) =&amp;gt; {
    const {addToCart} = useCartStore();

    return (
        &amp;lt;div className="w-3/4 p-4"&amp;gt;
          &amp;lt;h1 className="text-2xl font-bold mb-4 text-center"&amp;gt;Food Cart&amp;lt;/h1&amp;gt;
          &amp;lt;div className="grid grid-cols-1 md:grid-cols-2 gap-4"&amp;gt;
            {items.map((item) =&amp;gt; (
              &amp;lt;div
                key={item.name}
                className="border p-4 rounded-lg shadow-md flex flex-col items-center"
              &amp;gt;
                &amp;lt;img
                  src={item.image}
                  alt={item.name}
                  className="w-32 h-32 object-cover mb-4 rounded"
                /&amp;gt;
                &amp;lt;h2 className="text-lg font-semibold mb-2"&amp;gt;{item.name}&amp;lt;/h2&amp;gt;
                &amp;lt;p className="text-gray-600 mb-2"&amp;gt;{item.description}&amp;lt;/p&amp;gt;
                &amp;lt;p className="text-green-500 font-bold mb-2"&amp;gt;${item.price}&amp;lt;/p&amp;gt;
                &amp;lt;button className="p-2 rounded-full bg-blue-500 text-white hover:bg-blue-600" onClick={()=&amp;gt;addToCart(item)}&amp;gt;
                  &amp;lt;Plus className="w-5 h-5" /&amp;gt;
                &amp;lt;/button&amp;gt;
              &amp;lt;/div&amp;gt;
            ))}
          &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  };

export default FoodItems;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The FoodItems displays the item by looping over them and each item has a add button which calls the &lt;code&gt;addToCart&lt;/code&gt; function of useCartStore.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ShoppingCart.tsx&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Minus, Plus, ShoppingCart as ShoppingCartIcon } from "lucide-react";
import { useCartStore } from "./store/cartStore";

const ShoppingCart = ()=&amp;gt;{

  const {cart, incrementDecrementSku, clearCart, deleteSku} = useCartStore();

    return (&amp;lt;div className="w-1/4 p-4 bg-gray-100 shadow-md"&amp;gt;
          &amp;lt;div className="flex flex-col items-center"&amp;gt;
            &amp;lt;button className="p-4 rounded-full bg-gray-200 hover:bg-gray-300"&amp;gt;
              &amp;lt;ShoppingCartIcon className="w-8 h-8 text-gray-700" /&amp;gt;
            &amp;lt;/button&amp;gt;
            &amp;lt;button className="p-2 rounded-full bg-gray-200 hover:bg-gray-300 mt-1" onClick={clearCart}&amp;gt;
              Clear All
            &amp;lt;/button&amp;gt;
            &amp;lt;p className="mt-2 text-gray-700 font-semibold"&amp;gt;Your Cart&amp;lt;/p&amp;gt;
            {
              cart.map((sku)=&amp;gt;(
                &amp;lt;div key={sku.item.id}  className="bg-blue-200 p-2 px-3 rounded-lg m-2 min-w-full"&amp;gt;
                  &amp;lt;div className="flex items-center justify-between gap-2"&amp;gt;
                    {sku.item.name}
                    &amp;lt;QuantityControlButton count={sku.count} 
                    decrementBy1={()=&amp;gt; incrementDecrementSku(sku.item.id,'decrement')}
                    incrementBy1={()=&amp;gt; incrementDecrementSku(sku.item.id,'increment')}
                    /&amp;gt;
                  &amp;lt;/div&amp;gt;
                  &amp;lt;button className="border border-red-500 p-1 rounded-md" onClick={()=&amp;gt; deleteSku(sku.item.id)}&amp;gt;Delete&amp;lt;/button&amp;gt;
                &amp;lt;/div&amp;gt;
              ))
            }
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;)
}

export default ShoppingCart;

type QuantityControlButtonProps = {
  count: number;
  incrementBy1: ()=&amp;gt; void;
  decrementBy1: ()=&amp;gt; void;

}
export const QuantityControlButton = ({count, decrementBy1, incrementBy1}:QuantityControlButtonProps)=&amp;gt;{
  return (
    &amp;lt;div className="flex items-center justify-between border-2 gap-4 border-yellow-500 p-1 rounded-3xl"&amp;gt;
     &amp;lt;Minus size={16} onClick={decrementBy1} className="cursor-pointer"&amp;gt;&amp;lt;/Minus&amp;gt;
     {count}
     &amp;lt;Plus size={16} onClick={incrementBy1} className="cursor-pointer"&amp;gt;&amp;lt;/Plus&amp;gt;

    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the ShoppingCart, we are adding/removing/deleting items from the cart.&lt;/p&gt;

&lt;p&gt;Overall, Zustand helps us to write state management code in a leaner way compared to React-redux.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Facade Pattern</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Mon, 09 Sep 2024 16:36:46 +0000</pubDate>
      <link>https://dev.to/abhidatta0/facade-pattern-5h52</link>
      <guid>https://dev.to/abhidatta0/facade-pattern-5h52</guid>
      <description>&lt;p&gt;Facade pattern is relatively a simple design pattern to understand and heavily used in actual code.&lt;br&gt;
The word &lt;strong&gt;"Facade"&lt;/strong&gt; means "&lt;em&gt;the principal front of a building, that faces on to a street or open space.&lt;/em&gt;"&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What and why Facade Pattern ?&lt;/strong&gt;&lt;br&gt;
With the Facade pattern you can take a complex subsystem and making it easier to use by implementing a Facade class that provides a single but more reasonable interface.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Example&lt;/u&gt;&lt;br&gt;
Consider , you are designing a smart home system where your home can have subsystems like lights, thermostat, security system etc which controls various parts of your house.&lt;br&gt;
Now, if you have to turn on/off these systems when you arrive or leave the house &lt;strong&gt;you have to manually&lt;/strong&gt; do this things.&lt;br&gt;
You can get rid of these manual (and repeated) tasks by the a help of a Facade (or a  butler) who will internally call these methods and you will just call a single function of this Facade.&lt;/p&gt;

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

&lt;p&gt;&lt;u&gt;Code snippet 1&lt;/u&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Subsystems
class Light {
    turnOn() { console.log("Lights are on"); }
    turnOff() { console.log("Lights are off"); }
}

class Thermostat {
  setTemperature(temp: number) { 
    console.log(`Temperature set to ${temp}°C`); 
  }
}

class SecuritySystem {
    arm() { console.log("Security system armed"); }
    disarm() { console.log("Security system disarmed"); }
}

// Facade
class SmartHomeFacade {
    private light: Light;
    private thermostat: Thermostat;
    private security: SecuritySystem;

    constructor() {
        this.light = new Light();
        this.thermostat = new Thermostat();
        this.security = new SecuritySystem();
    }

    leaveHome() {
        this.light.turnOff();
        this.thermostat.setTemperature(18);
        this.security.arm();
        console.log("Home is set to 'Away' mode");
    }

    arriveHome() {
        this.security.disarm();
        this.light.turnOn();
        this.thermostat.setTemperature(22);
        console.log("Home is set to 'Welcome' mode");
    }
}

function test(){
    //  Client code
    const smartHome = new SmartHomeFacade();
    smartHome.leaveHome();
    console.log("---");
    smartHome.arriveHome();
}
test();

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

&lt;/div&gt;



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

&lt;p&gt;Code for this and other patterns can be found here: &lt;a href="https://github.com/abhidatta0/Essential-design-patterns-in-Typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/Essential-design-patterns-in-Typescript&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lets explain the code&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Light , Thermostat, SecuritySystem : these are three utilities which we are controlling in our house.The code for these is not much relevant to understand for the purpose of this blog.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;SmartHomeFacade: this class acts as the Facade between client and the 3 classes above and helps to control them internally. The client only calls the methods of the facade class.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the test function, we just invoke &lt;code&gt;leaveHome&lt;/code&gt; and &lt;code&gt;arriveHome&lt;/code&gt; methods of the SmartHomeFacade function and it will take care of the rest!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;br&gt;
Another benefit of using Facade class is it &lt;strong&gt;decouples a client from the subsytems&lt;/strong&gt;. For e.g: if the method name is changed in Light class , we only need to make change in the SmartHomeFacade class .The client code remains as it is!&lt;/p&gt;

&lt;h2&gt;
  
  
  That’s it 😅
&lt;/h2&gt;

&lt;p&gt;Code for this and other patterns can be found here: &lt;a href="https://github.com/abhidatta0/Essential-design-patterns-in-Typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/Essential-design-patterns-in-Typescript&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Adapter Design Pattern</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Sun, 04 Aug 2024 03:31:44 +0000</pubDate>
      <link>https://dev.to/abhidatta0/adapter-design-pattern-389f</link>
      <guid>https://dev.to/abhidatta0/adapter-design-pattern-389f</guid>
      <description>&lt;p&gt;This is part of the design pattern series in Typescript&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What and why adapter pattern is needed ?&lt;/strong&gt;&lt;br&gt;
The adapter pattern converts the interface of a class into another interface the client expects.Adapter lets classes work together that couldn't otherwise because of incomparable interfaces.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ok, that's a lot of jargon so lets break it down 🔨.&lt;/em&gt;  &lt;/p&gt;

&lt;p&gt;&lt;u&gt;Example&lt;/u&gt;&lt;br&gt;
Generally, we have two types of mobile charging ports - USB C and MicroUSB (or USB B).Their &lt;em&gt;interfaces&lt;/em&gt; (port structure) are different.&lt;/p&gt;

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

&lt;p&gt;Now, suppose you have a phone with MicroUSB port &lt;strong&gt;but you dont't have its cable&lt;/strong&gt;, but you have a USB C cable. So what you do ?&lt;br&gt;
You will get an adapter which lets you "convert" USBC to MicroUSB.&lt;/p&gt;

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

&lt;p&gt;&lt;u&gt;Code Snippet 1&lt;/u&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   function charge( usbc: USBCCharger){
     usbc.chargeByUSBC();
   }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here are four conceptual terms that we will need to know: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Adapter&lt;/strong&gt;: The connector which helps to adapt (or connect).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Target&lt;/strong&gt;: A class which will be converted from. In the code snippet 1, USBCCharger is the target.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Client&lt;/strong&gt;: Someone (the user) using  the Target class . In the code snippet 1, function &lt;code&gt;charge&lt;/code&gt; is the client.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Adaptee&lt;/strong&gt;: The class whose methods will actually be called by the adapter.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;u&gt;Code snippet 2&lt;/u&gt;&lt;br&gt;
Let us define a USBC class which has a charge method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class USBCCharger{
    chargeByUSBC(){
        console.log("charging by USBCCharger")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;u&gt;Code snippet 3&lt;/u&gt;&lt;br&gt;
Let us define a  MicroUSB class which also has a charge method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MicroUSBCharger{
    chargeByMicroUsb(){
        console.log("charging by MicroUSBCharger")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;u&gt;Code snippet 4&lt;/u&gt;&lt;br&gt;
Now, the adapter class which targets USBC charger so we can invoke &lt;code&gt;charge&lt;/code&gt; (of Code snippet 1) by using  MicroUSBCharger as an adaptee&lt;br&gt;
can be written as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class USBCAdapter implements USBCCharger{

    private usb:MicroUSBCharger;
    constructor(usb: MicroUSBCharger){
       this.usb = usb;
    }

    chargeByUSBC() {
        // can do conversions if needed etc.
        this.usb.chargeByMicroUsb();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;u&gt;Code snippet 5&lt;/u&gt;&lt;br&gt;
Here is the test code to test the Adapter pattern&lt;br&gt;
&lt;u&gt;Test&lt;/u&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function charge( usbc: USBCCharger){
   usbc.chargeByUSBC();
}

const usbC  = new USBCCharger();
charge(usbC);

const microUsb = new MicroUSBCharger();
const adapter = new USBCAdapter(microUsb);
charge(adapter);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdno3dctlxzgor73fjdex.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdno3dctlxzgor73fjdex.png" alt="Test code" width="800" height="138"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Code for this and other patterns can be found here: &lt;a href="https://github.com/abhidatta0/Essential-design-patterns-in-Typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/Essential-design-patterns-in-Typescript&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lets break down the USBCAdapter class&lt;/strong&gt; (Code Snippet 4).&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;class USBCAdapter implements USBCCharger&lt;/code&gt; -&amp;gt; The class  USBCAdapter implements USBCAdapter because this is what the client &lt;code&gt;charge&lt;/code&gt; of code snippet 1 expects&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;constructor(usb: MicroUSBCharger)&lt;/code&gt; -&amp;gt; Here while creating an instance of USBCAdapter we need to get the reference of the object we are adapting (in this example MicroUSBCharger)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;chargeByUSBC&lt;/code&gt; method -&amp;gt; Now we need to implement all the methods of the target class (USBCCharger) and translate them to adaptee class(MicroUSBCharger)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;&lt;br&gt;
Don't think of the Adapter class simply as a wrapper over Adaptee class.It is for the purpose of converting the interface of a class into another interface the client expects.&lt;/p&gt;

&lt;p&gt;The adapter pattern is a widely used design pattern in software engineering.It is often used when working with a legacy class and adapt it to a new class.&lt;/p&gt;

&lt;h2&gt;
  
  
  That’s it 😅
&lt;/h2&gt;

&lt;p&gt;Code for this and other patterns can be found here: &lt;a href="https://github.com/abhidatta0/Essential-design-patterns-in-Typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/Essential-design-patterns-in-Typescript&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Singleton design pattern</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Sun, 04 Aug 2024 03:30:48 +0000</pubDate>
      <link>https://dev.to/abhidatta0/singleton-design-pattern-3bm1</link>
      <guid>https://dev.to/abhidatta0/singleton-design-pattern-3bm1</guid>
      <description>&lt;p&gt;This is part of the design pattern series in Typescript.&lt;br&gt;
Code for this and other patterns can be found here: &lt;a href="https://github.com/abhidatta0/Essential-design-patterns-in-Typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/Essential-design-patterns-in-Typescript&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why singleton is needed ?&lt;/strong&gt;&lt;br&gt;
There are some cases where &lt;strong&gt;we need to ensure only one instance of a class exists&lt;/strong&gt;. &lt;br&gt;
e.g: Thread pools, Caches, Settings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Singleton Pattern ensures a class has only one instance, and provides a global point of access to it&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Example&lt;/u&gt;&lt;br&gt;
We know, every school has only one headmaster(or principal).&lt;br&gt;
Irrespective of the situation , where the headmaster is &lt;em&gt;called&lt;/em&gt; it should return the same person (or in code "instance").&lt;br&gt;
&lt;u&gt; &lt;strong&gt;Code&lt;/strong&gt;&lt;/u&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  class Headmaster{
    static uniqueInstance: Headmaster;
    public readonly name = "Albert Einstein";

    private constructor(){}

    static getInstance(): Headmaster{
      if(!Headmaster.uniqueInstance){
        Headmaster.uniqueInstance = new Headmaster();
      }
      return Headmaster.uniqueInstance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's break it down and explain.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;static uniqueInstance: Headmaster&lt;/code&gt; -&amp;gt; This is a static variable to hold our one instance.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;public readonly name = "Albert Einstein"&lt;/code&gt; -&amp;gt; This is a property of the instance. For singleton, every object will have same property values. &lt;code&gt;readonly&lt;/code&gt; so it cannot be modified from outside.&lt;/li&gt;
&lt;li&gt; &lt;code&gt;private constructor&lt;/code&gt; -&amp;gt; Our constructor is made private ; only class itself can instantiate this class!&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;static getInstance(): Headmaster&lt;/code&gt;-&amp;gt; This is a static method which returns a instance of Headmaster class.We first check if the &lt;code&gt;uniqueInstance&lt;/code&gt; is null or not.

&lt;ul&gt;
&lt;li&gt;If uniqueInstance &lt;strong&gt;is null&lt;/strong&gt;, we first create it via the private constructor and assign it to the uniqueInstance.
&lt;/li&gt;
&lt;li&gt;If uniqueInstance &lt;strong&gt;isn't null&lt;/strong&gt; , then it was previously created. We just fall through to the return statement.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const hm1 = Headmaster.getInstance(); //  instance 1
const hm2 = Headmaster.getInstance(); //  instance 2

console.log(hm1 === hm2); // will print true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;Eager vs Lazy creation&lt;/strong&gt;&lt;br&gt;
If your application always creates and uses an instance of the Singleton class or the overhead of instance creation is not much, you may want to create the Singleton eagerly.&lt;/p&gt;

&lt;p&gt;"Eager" means the instance will be created at the time of class creation in runtime.&lt;br&gt;
This will require slight modification of above code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Headmaster_Eager{
      static uniqueInstance: Headmaster_Eager = new Headmaster_Eager();   

      ...
      ...

    static getInstance(): Headmaster_Eager{
      return Headmaster_Eager.uniqueInstance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here , no need to check if uniqueInstance is null or not in getInstance() method.&lt;/p&gt;

&lt;p&gt;However, the eager way should be followed only if the object is always needed in your creation, otherwise it will waste memory.&lt;/p&gt;

&lt;p&gt;That’s it 😅&lt;/p&gt;




&lt;p&gt;Code for this and other patterns can be found here: &lt;a href="https://github.com/abhidatta0/Essential-design-patterns-in-Typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/Essential-design-patterns-in-Typescript&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Culture vs Free Food</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Tue, 28 Feb 2023 15:34:10 +0000</pubDate>
      <link>https://dev.to/abhidatta0/culture-vs-free-food-54l4</link>
      <guid>https://dev.to/abhidatta0/culture-vs-free-food-54l4</guid>
      <description>&lt;p&gt;Disclaimer: Ok, I know the title seems clickbaity but I want as many people to read it.&lt;/p&gt;

&lt;p&gt;What is culture or more specifically Company culture?&lt;br&gt;
I found a pretty practical definition of the term in this website &lt;br&gt;
&lt;a href="https://www.greatplacetowork.com/resources/blog/company-culture-meaning-benefits-and-strategies" rel="noopener noreferrer"&gt;https://www.greatplacetowork.com/resources/blog/company-culture-meaning-benefits-and-strategies&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;"Company culture is how you do what you do in the workplace. It’s the sum of your formal and informal systems and behaviors and values, all of which create an experience for your employees and customers."&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In short , it is the &lt;strong&gt;soul&lt;/strong&gt; of the workplace.&lt;/p&gt;

&lt;p&gt;So, here we go:&lt;br&gt;
Often times I have seen people(mostly) run behind certain companies just for the purpose of showing off or fancies like getting free food.&lt;/p&gt;

&lt;p&gt;But for the long term success of an individual in the company it is often the culture of the company.&lt;br&gt;
Unfortunately, the culture is a very abstract thing which is not immediately visible outside the company.But it can truly only be known from people already working in the company.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is a reason&lt;/strong&gt; (and a secret) why some companies believe in free food and giving out stuffs - It is less about employee benefit and more about marketing and PR.&lt;br&gt;
And the best evidence to this is the recent layoff news , those companies have started laying off their employees.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now why this happen?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;The money which is spent in providing this free food etc is ultimately coming from the company profit which gets dried up in bad times.&lt;/strong&gt;&lt;br&gt;
But a good culture can sustain any environment without losing any money.Although maintaining a good culture is very hard and simultaneously also hard to recover once damaged.&lt;/p&gt;

&lt;p&gt;To quote : "A good culture eats free food for breakfast".(No pun intended!)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Add custom fonts (Google Fonts) to React native(&gt;= 0.70)</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Sun, 25 Sep 2022 14:24:00 +0000</pubDate>
      <link>https://dev.to/abhidatta0/add-custom-fonts-google-fonts-to-react-native-070-1773</link>
      <guid>https://dev.to/abhidatta0/add-custom-fonts-google-fonts-to-react-native-070-1773</guid>
      <description>&lt;p&gt;Here, we will know how to add custom fonts to our react native app.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to Google Fonts website and select the font family (e.g: Montserrat)&lt;/li&gt;
&lt;li&gt;For a particular family, we can select multiple styles (e.g: Montserrat-Regular, Montserrat-Bold).After selecting, we click the "Download family" to download the font in a zip.&lt;/li&gt;
&lt;/ul&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We extract the zip file and inside the &lt;code&gt;static&lt;/code&gt; folder, we will get a list of styles with extensions .ttf . We copy the required fonts and create a folder in our react native project:  PROJECT ROOT/assets/fonts and paste the .ttf files there.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj1634x4pxuzh0u8cr4d4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj1634x4pxuzh0u8cr4d4.png" alt="fonts folder" width="306" height="144"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inside our project root create a file: &lt;code&gt;react-native.config.js&lt;/code&gt; and paste the following, to let know react-native where to get the fonts from.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
    project: {
        ios:{},
        android:{}
    },
    assets:['./assets/fonts/'],
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;One more step before starting your app build&lt;/strong&gt;, you need to link the asset, using &lt;code&gt;npx react-native-asset&lt;/code&gt; (enhancement over react-native link). This will automatically create assets/fonts folder (for android) and make a custom font entry in Info.plist (for ios).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Now, you can create a text style, by adding the newly added font.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const styles = StyleSheet.create({
  title:{
    fontFamily: 'Montserrat-Regular',
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

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




</description>
    </item>
    <item>
      <title>Understanding HOCs in React (in Typescript)</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Tue, 23 Aug 2022 14:37:00 +0000</pubDate>
      <link>https://dev.to/abhidatta0/understanding-hocs-in-react-in-typescript-42l2</link>
      <guid>https://dev.to/abhidatta0/understanding-hocs-in-react-in-typescript-42l2</guid>
      <description>&lt;p&gt;HOC stands for Higher-Order Components.&lt;br&gt;
It means a component which takes in another component and returns an &lt;em&gt;enhanced&lt;/em&gt; component.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;const HoC = Component =&amp;gt; EnhancedComponent&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The primary use case of HOC is to have a single place to sharing functionalities between components.&lt;br&gt;
(&lt;strong&gt;Think of HOC more like a function, than component&lt;/strong&gt;, this will be more clear as we go.)&lt;/p&gt;

&lt;p&gt;Suppose, you have a requirement to calculate the innerWidth of browser viewport as it is resized and then do some computations/ui change.&lt;/p&gt;

&lt;p&gt;For our example, we just want to display the window.innerWidth in "realtime".&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc64objdmrsda1eupwz1m.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc64objdmrsda1eupwz1m.gif" alt="Demo" width="800" height="456"&gt;&lt;/a&gt;&lt;br&gt;
To achieve this we can write a functional component and use the useEffect hook and attach a listener function which will update a state variable.&lt;br&gt;
See code: &lt;a href="https://github.com/abhidatta0/react-hoc-in-typescript/blob/master/src/ResizeComponent.tsx" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/react-hoc-in-typescript/blob/master/src/ResizeComponent.tsx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, suppose we have to use this logic in another component.In that case, we have to duplicate our logic 😞 (which is obviously bad).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What could be a better(or best) way?&lt;/strong&gt;&lt;br&gt;
We can just abstract away this useEffect and listener code into another component and expose the innerWidth variable as a prop.&lt;br&gt;
This "special" component is our Higher-Order Component.&lt;/p&gt;

&lt;p&gt;withResize.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const withResize = (Component: FC&amp;lt;any&amp;gt; )=&amp;gt; (props: any)=&amp;gt; {
    const  [innerWidth, setInnerWidth] = useState(0);

    const handleResize = ()=&amp;gt;{
     setInnerWidth(window.innerWidth);
    }

    useEffect(()=&amp;gt;{
     window.addEventListener('resize', handleResize);

     return ()=&amp;gt;{
       window.removeEventListener('resize', handleResize);
     }
    },[]); 

    return &amp;lt;Component {...props} windowInnerWidth={innerWidth} /&amp;gt;
}

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

&lt;/div&gt;



&lt;p&gt;WithResizeUsage.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const WithResizeUsage = ({name, windowInnerWidth}: {name: string, windowInnerWidth: number})=&amp;gt;{
    return (
        &amp;lt;div&amp;gt;Inner Width is {windowInnerWidth} and name is {name}&amp;lt;/div&amp;gt;
    )
}

export default withResize(WithResizeUsage);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;App.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;WithResizeUsage name="Developer" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's analyze what we have written&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In App.tsx, we call WithResizeUsage with a name prop.&lt;/li&gt;
&lt;li&gt;withResize is an hoc, which takes in a Component which itself accepts some props.&lt;/li&gt;
&lt;li&gt;The return of withResize is a component with all its original props and the extra &lt;code&gt;windowInnerWidth&lt;/code&gt; prop.&lt;/li&gt;
&lt;li&gt;In WithResizeUsage: we accept the &lt;code&gt;name&lt;/code&gt; prop that we get from App.tsx and the &lt;code&gt;windowInnerWidth&lt;/code&gt; that we get from &lt;code&gt;withResize&lt;/code&gt; hoc.&lt;/li&gt;
&lt;li&gt;In WithResizeUsage, we wrap it with withResize in the last line &lt;code&gt;withResize(WithResizeUsage)&lt;/code&gt; to bind it with withResize.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;See code:&lt;br&gt;
&lt;a href="https://github.com/abhidatta0/react-hoc-in-typescript/blob/master/src/withResize.tsx" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/react-hoc-in-typescript/blob/master/src/withResize.tsx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/abhidatta0/react-hoc-in-typescript/blob/master/src/WithResizeUsage.tsx" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/react-hoc-in-typescript/blob/master/src/WithResizeUsage.tsx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Notice how clean our WithResizeUsage component becomes.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's look at how we can enhance the HOC a bit more.&lt;br&gt;
Suppose, we need that that the displayed window.innerWidth is x amount more and x value will be configurable.If inner width is 90 and x is 3, we will display 93.&lt;/p&gt;

&lt;p&gt;We will modify the HOC by adding another level to accept additional params.(This concept is called &lt;strong&gt;function currying&lt;/strong&gt;)  &lt;/p&gt;

&lt;p&gt;withResizeAdvanced.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Params =  {
  bumped: number;
}
const withResizeAdvanced = (params: Params)=&amp;gt; (Component: FC&amp;lt;any&amp;gt; )=&amp;gt; (props: any)=&amp;gt; {
    console.log(params);
    const  [innerWidth, setInnerWidth] = useState(0);

    const handleResize = ()=&amp;gt;{
     setInnerWidth(window.innerWidth+params.bumped);
    }

    useEffect(()=&amp;gt;{
     window.addEventListener('resize', handleResize);

     return ()=&amp;gt;{
       window.removeEventListener('resize', handleResize);
     }
    },[]); 

    return &amp;lt;Component {...props} windowInnerWidth={innerWidth} /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;withResizeAdvancedUsage.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import withResizeAdvanced from "./withResizeAdvanced";

const WithResizeUsage = ({name, windowInnerWidth}: {name: string, windowInnerWidth: number})=&amp;gt;{
    return (
        &amp;lt;div&amp;gt;Inner Width is {windowInnerWidth} and name is {name}&amp;lt;/div&amp;gt;
    )
}

export default withResizeAdvanced({bumped: 5})(WithResizeUsage);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;App.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      &amp;lt;WithResizeAdvancedUsage name="Developer"/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Everything is similar to earlier HOC, except we can pass a object which has a property &lt;code&gt;bumped&lt;/code&gt; can we use to modify the innerWidth.&lt;/p&gt;

&lt;p&gt;If we put earlier and the new component in App.tsx, we can visualize that for the later one, innerWidth is incremented by 5.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6f0iuc02oajvfj3bzqek.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6f0iuc02oajvfj3bzqek.gif" alt="HOC bumped" width="760" height="433"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Github repo: &lt;a href="https://github.com/abhidatta0/react-hoc-in-typescript" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/react-hoc-in-typescript&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Make sure HOC have the general logic (like getting window.innerWidth) will be reused across other components.
&lt;/li&gt;
&lt;li&gt;An alternative to HOC pattern for function component is to use custom hooks. &lt;/li&gt;
&lt;/ul&gt;




</description>
    </item>
    <item>
      <title>Javascript Symbol</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Sun, 19 Jun 2022 13:12:05 +0000</pubDate>
      <link>https://dev.to/abhidatta0/javascript-symbol-396</link>
      <guid>https://dev.to/abhidatta0/javascript-symbol-396</guid>
      <description>&lt;p&gt;A symbol is a primitive data type in Javascript, introduced in ES6.&lt;br&gt;
A symbol is created using the &lt;code&gt;Symbol&lt;/code&gt; constructor.The string is optional.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let sym1 = Symbol('xyz');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One important behaviour of symbol it return a unique value.&lt;br&gt;
So, the below code will log false&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let sym1 = Symbol('foo');
let sym2 = Symbol('foo');

sym1 === sym2;  // false
typeof sym1;    // symbol
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: using the &lt;code&gt;new&lt;/code&gt; operator will throw a TypeError. This is called &lt;code&gt;incomplete constructor&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let sym = new Symbol('foo');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Uncaught TypeError: Symbol is not a constructor&lt;/code&gt;&lt;/p&gt;




&lt;p&gt;When symbol-ed keys are used in object, using &lt;code&gt;for...in&lt;/code&gt; will ignore those keys. Even they would be ignored by &lt;code&gt;Object.keys&lt;/code&gt;, but &lt;code&gt;Object.getOwnPropertySymbols&lt;/code&gt; function can be used to get these.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let obj = {};

obj[Symbol('foo')] = 'a'
obj[Symbol.for('bar')] = 'b';
obj['c'] = 'c';
obj.d = 'd';

for(let i in obj){
   console.log(i);   // logs c,d
}

Object.keys(obj);     // ['c', 'd']
Object.getOwnPropertySymbols(obj);  // [Symbol(foo), Symbol(bar)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Symbol.for and Symbol.keyFor
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;Symbol.for(string)&lt;/code&gt; is a function that checks for  a symbol in the Global Symbol Registry(GSR) and returns it. If not present, it creates and returns it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Symbol.keyFor(symbol)&lt;/code&gt; function is used to retrieve the identifier of the symbol, created using Symbol.for.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const foo1 = Symbol.for('foo');  // this one is created
const foo2 = Symbol.for('foo');  // retrieve the already created one
const bar = Symbol.for('bar');   // this one is created


foo1 === foo2;    // true
foo1 === bar;     // false
Symbol.keyFor(foo1)  // "foo"

const empty = Symbol.for();
console.log(Symbol.keyFor(empty));  // "undefined" (string)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that, since Symbol.keyFor retrieves symbol from GSR, symbol created by the Symbol constructor is not accessible by keyFor and hence return undefined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Jam = Symbol('jam');
console.log(Symbol.keyFor(Jam));   // undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Usage in React
&lt;/h3&gt;

&lt;p&gt;Symbol can be used in trigger change detection, generally used in useEffect.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [key, setKey] = useState(Symbol());

const changeKey = ()=&amp;gt;{
  setKey(Symbol());   // new value is set
}

useEffect(()=&amp;gt;{
  // anything to run on change of "key"
},[key]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






</description>
    </item>
    <item>
      <title>Tagged functions / Tagged templates</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Wed, 15 Jun 2022 03:32:48 +0000</pubDate>
      <link>https://dev.to/abhidatta0/tagged-functions-tagged-templates-57hc</link>
      <guid>https://dev.to/abhidatta0/tagged-functions-tagged-templates-57hc</guid>
      <description>&lt;p&gt;According to MDN docs&lt;br&gt;
&lt;em&gt;Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.&lt;/em&gt;&lt;br&gt;
Let's explore more here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const age = 20;
function name(...args){
  console.log(args);
}
name`My Name is ${age}`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This outputs&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frjkeva679ermmkfd5mo9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frjkeva679ermmkfd5mo9.png" alt="Tagged templates" width="442" height="154"&gt;&lt;/a&gt;&lt;br&gt;
So, we see the arguments of the tagged template &lt;code&gt;name&lt;/code&gt; is an array which contains the string literals as an array as first element and the remaining arguments are related to the expression.&lt;/p&gt;

&lt;p&gt;This abilty of processing, enables powerful features like the&lt;br&gt;
Styled component syntax.&lt;/p&gt;

&lt;p&gt;Let us see an example.&lt;br&gt;
Suppose we have template string which has some expressions bounded in one div and we want to separate out each expression in their own divs.&lt;br&gt;&lt;br&gt;
For this we can write a tagged template which return the processed string and then we can use document.body to put it on DOM.&lt;br&gt;&lt;br&gt;
Here is the code&lt;br&gt;
&lt;a href="https://jsfiddle.net/abkhfmtz/21/" rel="noopener noreferrer"&gt;https://jsfiddle.net/abkhfmtz/21/&lt;/a&gt;&lt;/p&gt;


&lt;h1&gt;
  
  
  One pitfall to remember
&lt;/h1&gt;

&lt;p&gt;Because tagged template can parse unicode representation, a invalid unicode will print &lt;code&gt;undefined&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function name(stringExps){
   console.log(stringExps);
}

name`\u00A9`
name`\xA9`
name`\unicode`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first two function call will print &lt;code&gt;©&lt;/code&gt; but the last one will print undefined.&lt;/p&gt;




</description>
    </item>
    <item>
      <title>Template literals in Javascript</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Tue, 14 Jun 2022 03:58:19 +0000</pubDate>
      <link>https://dev.to/abhidatta0/template-literals-in-javascript-1glc</link>
      <guid>https://dev.to/abhidatta0/template-literals-in-javascript-1glc</guid>
      <description>&lt;p&gt;A sample template literal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const x = `This is template literal`;
console.log(x);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which will print&lt;/p&gt;

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

&lt;p&gt;Template literal is mainly used in two ways&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;String interpolation&lt;/li&gt;
&lt;li&gt;Tagged functions or Tagged templates&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this blog, we will discuss about String interpolation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const human = {
   age: 28,
   country: 'India'
}
const intro = `My age is ${human.age} and I am from ${human.country}`;
console.log(intro);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are interpolating the name and age property of human object.&lt;/p&gt;

&lt;p&gt;If we try to use single quoted(or double quoted) strings we have to write this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const intro = 'My age is '+human.age+' and I am from '+human.country;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  We can write any javascript logic between the ${ }.
&lt;/h3&gt;

&lt;p&gt;This enable us to write easily understandable logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const human = {
   age: 28,
   country: 'India'
}
const intro = `I am ${human.age &amp;gt; 20 ? 'adult' : 'juvenile'}`
console.log(intro);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The equivalent of writing this in single quote&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const human = {
   age: 28,
   country: 'India'
}
const intro = 'I am '+ ( human.age &amp;gt; 20 ? 'adult' : 'juvenile' );
console.log(intro);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;String interpolation can be useful in React JSX when writing conditional  className.&lt;br&gt;
Suppose, we want to apply &lt;code&gt;btn-highlight&lt;/code&gt; when the button is to be highlighted and &lt;code&gt;btn&lt;/code&gt; as a normal button. We can take the &lt;code&gt;btn&lt;/code&gt;as a common word and append &lt;code&gt;-highlight&lt;/code&gt; as per condition.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/jzog2t"&gt;
&lt;/iframe&gt;
&lt;/p&gt;




</description>
    </item>
    <item>
      <title>Some less known features in Chrome Devtools</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Wed, 02 Mar 2022 05:18:00 +0000</pubDate>
      <link>https://dev.to/abhidatta0/some-less-known-features-in-chrome-devtools-1p3</link>
      <guid>https://dev.to/abhidatta0/some-less-known-features-in-chrome-devtools-1p3</guid>
      <description>&lt;p&gt;Here we will be exploring some less known features which I recently came to know about chrome devtools and I thought about sharing them. &lt;/p&gt;

&lt;p&gt;[Currently, I am using Chrome 98, to check your version go to &lt;strong&gt;chrome://settings/help&lt;/strong&gt;].&lt;/p&gt;

&lt;h4&gt;
  
  
  If you come across some more features, please add them in the comments.
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;More devices&lt;/strong&gt;
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxzfb8zvdrsmawbohj4it.png" alt="More devices" width="800" height="74"&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1be42xeipi5wzc018qy2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1be42xeipi5wzc018qy2.png" alt=" More devices" width="800" height="554"&gt;&lt;/a&gt;&lt;br&gt;
Chrome gives us ability to add more devices to test our webpage on.&lt;br&gt;
Go to Settings -&amp;gt; Devices -&amp;gt; check/uncheck to add/remove devices.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Web accessibilty&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Accessibility of a particular element (e.g: h1,p etc.) can be known by clicking on the "Accessibilty" tab on the elements tab.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Network tab&lt;/strong&gt; 
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsynuoud6dmssaohffsld.png" alt="Network tab" width="800" height="141"&gt;
Preserve Logs - To save requests across page loads, check the Preserve log.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Disable cache - By checking this box, we can more accurately emulate a first-time user's experience, because requests are served from the browser cache on repeat visits.&lt;/p&gt;




&lt;p&gt;That's it. Ciao!&lt;/p&gt;

</description>
      <category>browser</category>
      <category>css</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Adding slices, reducer,actions and finishing up!</title>
      <dc:creator>Abhirup Datta</dc:creator>
      <pubDate>Sun, 20 Feb 2022 13:45:07 +0000</pubDate>
      <link>https://dev.to/abhidatta0/adding-slices-reduceractions-and-finishing-up-2nee</link>
      <guid>https://dev.to/abhidatta0/adding-slices-reduceractions-and-finishing-up-2nee</guid>
      <description>&lt;p&gt;Our slice to handle our fruits state will be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {createSlice} from '@reduxjs/toolkit';

const initialState = {fruits: []};

const fruitsSlice = createSlice({
    name: 'fruits',
    initialState,
    reducers:{
        addFruit(state, action){
            console.log(action);
            state.fruits = [...state.fruits, action.payload];
        }
    }
});

export const {addFruit} = fruitsSlice.actions;
export default fruitsSlice;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can dispatch an action to update the addFruits reducer by calling it with the same name action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const addFruitHandler = ()=&amp;gt;{
   setError(null);
   if(fruitName.length &amp;gt; 0 &amp;amp;&amp;amp; Number.isInteger(fruitCount) &amp;amp;&amp;amp; fruitCount &amp;gt; 0){
            console.log(fruitName, fruitCount);
            dispatch(addFruit({fruitName, fruitCount}));  //dispatching action
   }
   ......
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets breakdown what happening,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Our fruits slice is created from &lt;code&gt;createSlice&lt;/code&gt; function provided by the RTK library.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;createSlice&lt;/code&gt; accepts an object with three mandatory properties: name, initialState, reducers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;name&lt;/code&gt; is used when dispatching an action.(more on this later).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;initialState&lt;/code&gt; is the initial state that this reducer will have.In our example, I have given an initial state.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;const initialState = {fruits: []}&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Note: &lt;small&gt;Use &lt;code&gt;null&lt;/code&gt; if we want to set initialState as empty.&lt;/small&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;reducers&lt;/code&gt; is an object containing Redux "case reducer" functions.It will have one or more actions depending on our application requirement.Here,I am creating one action &lt;code&gt;addFruit&lt;/code&gt; to add a fruit object to our existing fruit list.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Finally, we are exporting the actions of this slice and the fruitSlice.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;We will now link the reducer from fruitsSlice in our store.&lt;/p&gt;

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

&lt;p&gt;We can architect our code better by extracting out the actions in its own file.&lt;br&gt;
Create a folder &lt;code&gt;actions&lt;/code&gt; in our src folder and add a new file &lt;code&gt;fruits.js&lt;/code&gt; inside it.&lt;/p&gt;

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

&lt;p&gt;Let us take a deep look at the &lt;code&gt;name&lt;/code&gt; of the slice and dispatch code inside &lt;code&gt;AddFruit.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dispatch(addFruit({fruitName, fruitCount}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are dispatching an object with fruitName and fruitCount.&lt;br&gt;
By default, the action object of &lt;code&gt;addFruit&lt;/code&gt; reducer will be &lt;br&gt;
&lt;code&gt;{type: "fruits/addFruit", payload: {fruitName: 'peach', fruitCount: 1}&lt;br&gt;
&lt;/code&gt;.&lt;br&gt;
Type is formed by &lt;code&gt;&amp;lt;slice name&amp;gt;/&amp;lt;action name&amp;gt;&lt;/code&gt;&lt;br&gt;
and payload is the parameter we pass in the dispatch function.&lt;/p&gt;

&lt;p&gt;There is a bit of issue in the way we are dispatching our fruit name and count.&lt;br&gt;
We have to make sure other components also dispatch with same object structure({fruitName:'',fruitCount:''}) which is a bad practice.&lt;br&gt;
For that we create a custom payload by modifying our slice action,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruitsSlice = createSlice({
    ....
    reducers:{
        addFruit:{
            reducer: (state, action)=&amp;gt;{
                state.fruitList = [...state.fruitList, action.payload];
            },
            prepare: (name, count)=&amp;gt;{
                return {payload: {name, count}};
            }
        }
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and our dispatch will now simply be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dispatch(addFruit(fruitName, fruitCount));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The prepare method can accept any paramaters and returns a custom payload.&lt;/p&gt;

&lt;p&gt;Now, we will be &lt;em&gt;consuming&lt;/em&gt; the fruit list from our fruits state in FruitList component. &lt;/p&gt;

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

&lt;p&gt;That's it!&lt;/p&gt;




&lt;h4&gt;
  
  
  The final application can be found here:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://github.com/abhidatta0/fruits-logger-redux-toolkit" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/fruits-logger-redux-toolkit&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  The complete code can be found here:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://github.com/abhidatta0/fruits-logger-redux-toolkit" rel="noopener noreferrer"&gt;https://github.com/abhidatta0/fruits-logger-redux-toolkit&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
