<?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: Arul Valan Anto S</title>
    <description>The latest articles on DEV Community by Arul Valan Anto S (@arulvalananto).</description>
    <link>https://dev.to/arulvalananto</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%2F523102%2F8e895313-8aa7-45f4-a12f-dbcf057b6b2d.jpg</url>
      <title>DEV Community: Arul Valan Anto S</title>
      <link>https://dev.to/arulvalananto</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/arulvalananto"/>
    <language>en</language>
    <item>
      <title>9 Image Optimization Tricks for a Seamless Web Experience</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Mon, 24 Jul 2023 18:37:57 +0000</pubDate>
      <link>https://dev.to/arulvalananto/9-image-optimization-tricks-for-a-seamless-web-experience-29dc</link>
      <guid>https://dev.to/arulvalananto/9-image-optimization-tricks-for-a-seamless-web-experience-29dc</guid>
      <description>&lt;p&gt;In this article, We will explore effective image optimization techniques that significantly improve your web app’s performance. So let’s delve right in!&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Image Formats
&lt;/h2&gt;

&lt;p&gt;Choosing the right image format for each type of image can significantly impact the image’s file size and quality. Here’s the list of different image formats you can use for your app.&lt;/p&gt;

&lt;h3&gt;
  
  
  a. WebP
&lt;/h3&gt;

&lt;p&gt;WebP is an image format developed by Google that offers better compression and smaller file sizes compared to JPEG and PNG. It is supported by most modern browsers (excluding some versions of Safari and Internet Explorer). To use WebP, you can provide both WebP and fallback formats like JPEG or PNG in your HTML.&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;!-- 👇 Set image sources with different formats in the `srcSet` 
      the attribute in order of preference --&amp;gt;
&amp;lt;!-- 👇 Fallback image source for browsers that don't 
      support srcSet in `src` attribute  --&amp;gt;
&amp;lt;img
 srcset="car.webp, car.jpg"
 src="car.jpg"
 alt="Car"
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--N0TcbnIG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vb9akhnqbvp65iqnjb9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--N0TcbnIG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vb9akhnqbvp65iqnjb9.png" alt="Can I use — https://caniuse.com/webp" width="800" height="488"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  b. JPEG 2000
&lt;/h3&gt;

&lt;p&gt;JPEG 2000 is another high-quality image format with good compression. However, its support in browsers is limited. Similar to WebP, you can provide a JPEG 2000 version and fallback formats.&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;img
 srcset="car.jp2, car.jpg"
 src="car.jpg"
 alt="Car"
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4rBgdxEn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjx50ylx1hnz1d5plmwl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4rBgdxEn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zjx50ylx1hnz1d5plmwl.png" alt="Can I use — https://caniuse.com/jpeg2000" width="800" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  c. AVIF
&lt;/h3&gt;

&lt;p&gt;AVIF is a newer image format that provides excellent compression and image quality. It is supported in modern browsers like Chrome and Firefox.&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;img
 srcset="car.avif, car.jpg"
 src="car.jpg"
 alt="Car"
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--G8fr_XkG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2t2das9614ztajkv3fk2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--G8fr_XkG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2t2das9614ztajkv3fk2.png" alt="Can I use — https://caniuse.com/avif" width="800" height="431"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While WebP and AVIF are supported in modern browsers, JPEG 2000 has limited support. Therefore, it’s essential to test your website or application across different browsers to ensure proper image display for all users.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Responsive Images
&lt;/h2&gt;

&lt;p&gt;Responsive images allow you to serve different images based on the user’s device and screen size. This prevents large images from being loaded on smaller screens, saving bandwidth. Use the srcset and sizes attributes in the img element to achieve this:&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;img src="small.jpg"
  srcset="medium.jpg 800w,
          large.jpg 1200w,
          xlarge.jpg 1600w"
  sizes="(max-width: 600px) 100vw,
         (max-width: 1200px) 50vw,
         33vw"
  alt="Responsive Image"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;sizes — Informs the browser of the image's intended display size based on media queries. It doesn't affect which image the browser chooses to download. srcset — Lists multiple image sources with width descriptors (800w). Each width descriptor represents the actual width of the image in pixels. When the browser encounters both attributes (sizes and srcset), it follows these steps:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It evaluates the sizes attribute to determine the image's intended display size based on the device's viewport width.&lt;/li&gt;
&lt;li&gt;It then uses this calculated size, along with the available width descriptors in srcset, to decide which image to download. The browser picks the image with the closest width descriptor (closest to the calculated size) from the srcset.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Lazy Loading
&lt;/h2&gt;

&lt;p&gt;Lazy loading is a method that postpones the loading of images until they are about to become visible within the user’s viewport. This reduces the initial page load time. Use the loading="lazy" attribute on the img element (by default loading attribute is set as eager)&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;img src="image.jpg" alt="Image" loading="lazy"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Preloading and Caching
&lt;/h2&gt;

&lt;p&gt;Preload critical images to reduce the delay when they are actually needed. Use the link tag with rel="preload" in the head of your HTML:&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;link rel="preload" href="image.jpg" as="image"&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;Additionally, consider using service workers to cache images for subsequent visits. The following is a basic example of using a service worker to cache images&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Service worker code (sw.js)
self.addEventListener('install', event =&amp;gt; {
  event.waitUntil(
    caches.open('images-cache').then(cache =&amp;gt; {
      return cache.addAll([
        'image.jpg',
        'other-image.jpg',
        // Add more images to the cache here
      ]);
    })
  );
});

self.addEventListener('fetch', event =&amp;gt; {
  event.respondWith(
    caches.match(event.request).then(response =&amp;gt; {
      return response || fetch(event.request);
    })
  );
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a React app, you can use the react-helmet package to add the preload link in the HTML head section for critical images&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { Helmet } from 'react-helmet';
import PreloadImage from './assets/preload-image.png';

const ImageComponent = () =&amp;gt; {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;Helmet&amp;gt;
        &amp;lt;link rel="preload" href={PreloadImage} as="image" /&amp;gt;
      &amp;lt;/Helmet&amp;gt;
      &amp;lt;img src={PreloadImage} alt="Preload image alt" /&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Image Sprites
&lt;/h2&gt;

&lt;p&gt;An image sprite sheet is a single image that contains multiple smaller images or icons. It’s used to reduce the number of HTTP requests when rendering numerous small images on a web page. By loading a single sprite sheet, you can display specific images by adjusting the CSS background-position.&lt;/p&gt;

&lt;p&gt;Suppose you are building a social media web application and want to display various icons for actions such as liking a post, commenting, and sharing. Each icon is a small image that is typically used in different parts of the application.&lt;/p&gt;

&lt;h3&gt;
  
  
  Without Image Sprites:
&lt;/h3&gt;

&lt;p&gt;In a traditional approach, you would include each icon as a separate image file in your HTML or CSS, like this:&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;!-- Separate images for each icon --&amp;gt;
&amp;lt;img src="like-icon.png" alt="Like"&amp;gt;
&amp;lt;img src="comment-icon.png" alt="Comment"&amp;gt;
&amp;lt;img src="share-icon.png" alt="Share"&amp;gt;
&amp;lt;!-- and so on... --&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  With Image Sprites:
&lt;/h3&gt;

&lt;p&gt;Using image sprites, you can combine all these icons into a single sprite sheet, reducing the number of HTTP requests. Here’s an example of how it would look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* CSS using image sprites */
.icon {
  background-image: url("icons-sprite.png");
  background-repeat: no-repeat;
}

.like-icon {
  background-position: 0 0;
  width: 24px;
  height: 24px;
}

.comment-icon {
  background-position: -24px 0;
  width: 24px;
  height: 24px;
}

.share-icon {
  background-position: -48px 0;
  width: 24px;
  height: 24px;
}

/* and so on... */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="icon like-icon"&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class="icon comment-icon"&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class="icon share-icon"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, all the icons (like, comment, share, etc.) are combined into a single icons-sprite.png sprite sheet. The CSS classes (e.g., .like-icon, .comment-icon, .share-icon) use the background-position property to display the correct part of the sprite sheet as the background for each icon.&lt;/p&gt;

&lt;p&gt;Benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Instead of loading multiple image files, the web application now loads just one image (icons-sprite.png), reducing the number of HTTP requests.&lt;/li&gt;
&lt;li&gt;The sprite sheet is loaded once and can be cached by the browser, improving subsequent page loads.&lt;/li&gt;
&lt;li&gt;CSS classes control the display of individual icons from the sprite sheet, allowing for seamless hover and rollover effects without additional loading delays.&lt;/li&gt;
&lt;li&gt;This leads to faster and more efficient user experiences with improved overall page loading times.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. Adaptive Image Serving
&lt;/h2&gt;

&lt;p&gt;Adaptive Image Serving is a technique used in web development to deliver images that are optimized for the user’s specific device and network conditions. Adaptive image serving aims to provide the best possible image quality while minimizing the image file size and ensuring optimal performance.&lt;/p&gt;

&lt;p&gt;It is typically handled by a CDN or image server with dynamic resizing capabilities, and the implementation details may vary based on the chosen service. For instance, if you prefer to utilize AWS CloudFront, refer to this link for further information on image optimization: AWS Blog — &lt;a href="https://aws.amazon.com/blogs/networking-and-content-delivery/image-optimization-using-amazon-cloudfront-and-aws-lambda/"&gt;Image Optimization using Amazon CloudFront and AWS Lambda.&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Remove metadata
&lt;/h2&gt;

&lt;p&gt;Removing metadata from images is an essential step in image optimization. Because Image metadata can sometimes take up a significant portion of an image’s file size, especially for images captured by digital cameras or smartphones, by removing metadata, you can significantly reduce the overall file size of the image, leading to faster image loading on web pages. Tools like ImageMagick or online image metadata remover can help with this.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Use SVG for icons and logos
&lt;/h2&gt;

&lt;p&gt;SVGs are ideal for simple icons and logos because they are vector-based and can be scaled without losing quality.&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;!-- logo.svg --&amp;gt;
&amp;lt;svg width="100" height="100" viewBox="0 0 100 100"&amp;gt;
  &amp;lt;circle cx="50" cy="50" r="40" fill="blue" /&amp;gt;
&amp;lt;/svg&amp;gt;

&amp;lt;!-- index.html --&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using SVG for logos and icons provides a lightweight, scalable, and visually appealing solution that improves web page performance, ensures crisp visuals, and enhances the overall user experience across various devices and browsers.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Image Dimensions
&lt;/h2&gt;

&lt;p&gt;Specifying the image’s dimensions in HTML or CSS is essential to prevent layout shifts and improve page rendering speed. By specifying the image’s dimensions in HTML or CSS, you provide the browser with the necessary information to allocate the correct space for the image during the initial rendering process.&lt;/p&gt;

&lt;p&gt;Benefits&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Prevents Layout Shifts: Specifying the dimensions ensures that the browser knows the image’s exact size before loading it, preventing sudden layout shifts.&lt;/li&gt;
&lt;li&gt;Faster Page Rendering: With the image dimensions known in advance, the browser can render the layout more efficiently, leading to faster page loading times.&lt;/li&gt;
&lt;li&gt;Improved User Experience: By eliminating layout shifts, users have a more consistent and pleasant browsing experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To specify the image dimensions, you can directly include the width and height attributes within the img tag or apply a specific style by adding a class attribute to the img tag in CSS.&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;img src="logo.jpg" alt="logo" width="300" height="200" /&amp;gt;

&amp;lt;!-- or --&amp;gt;

.logo {
  width: 300px;
  height: 200px;
}

&amp;lt;img src="logo.jpg" alt="logo" class="logo" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Bonus
&lt;/h2&gt;

&lt;p&gt;Apart from the techniques mentioned above, You can utilize techniques like Blurhash for Placeholder Images, Progressive Image Loading for gradual quality improvement(where the image is initially displayed in low resolution and progressively improves in quality as it fully loads), and Automatic Image Compression with Image CDN for faster loading.&lt;/p&gt;

&lt;p&gt;I hope you really enjoyed it and learned some valuable techniques. There are many other techniques for image optimization that I didn’t cover, so feel free to explore them. If you know of any additional techniques I haven’t mentioned, please leave a comment.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; Keep coding.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>web</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
    </item>
    <item>
      <title>All You Need to Know about Decorators in TypeScript</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Mon, 10 Jul 2023 08:33:43 +0000</pubDate>
      <link>https://dev.to/arulvalananto/all-you-need-to-know-about-decorators-in-typescript-5dbi</link>
      <guid>https://dev.to/arulvalananto/all-you-need-to-know-about-decorators-in-typescript-5dbi</guid>
      <description>&lt;p&gt;This article will concentrate on Decorators, one of the features in TypeScript. We will delve into its details and explore its functionality using real-life examples. Let’s go!&lt;/p&gt;

&lt;p&gt;Decorators are a feature in TypeScript that allows you to add metadata and modify the behavior of classes, methods, properties, and parameters at compile time. Decorators are functions that are prefixed with the @ symbol.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: decorators are an experimental feature in TypeScript. To enable decorators in your TypeScript project, you must enable the "experimentalDecorators" compiler option in your tsconfig.json file.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// tsconfig.json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    // other compiler options...
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay. Let’s see a simple example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function uppercase(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    const result = originalMethod.apply(this, args);

    if (typeof result === "string") {
       return result.toUpperCase();
    }

    return result;
  };

  return descriptor;
}

class User {
  private name: string;

  constructor(name) {
    this.name = name;
  }

  // In this code, the uppercase decorator is applied to the getName method 
  // of the User class using the @uppercase syntax. 
  // This means that whenever the getName method is called, 
  // the uppercase decorator function will be invoked.
  @uppercase
  getName() {
    return this.name
  }
}

const user = new User("Arul Valan Anto");
console.log(user.getName());

// 🚀 output
// ARUL VALAN ANTO
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the decorator function named uppercase. It takes three parameters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;target: any: The target object or class on which the decorator is applied.&lt;/li&gt;
&lt;li&gt;propertyKey: string: The name of the property or method being decorated.&lt;/li&gt;
&lt;li&gt;descriptor: PropertyDescriptor: The property descriptor of the decorated property or method.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Use cases
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Logging and debugging&lt;/strong&gt;: You can use decorators to add logging statements or debug information around methods or functions, helping you track the execution flow and inspect values during development.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Validation and data transformation&lt;/strong&gt;: Decorators can validate the input parameters of methods or ensure the correctness of data properties.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Authorization and access control&lt;/strong&gt;: Decorators can check user permissions or apply access control rules to methods or classes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Dependency injection&lt;/strong&gt;: Decorators can be used in conjunction with dependency injection frameworks to automatically inject dependencies into classes. This practice is commonly observed in various places, notably within the Angular framework.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;API documentation&lt;/strong&gt;: Decorators can be used for generating API documentation and configuring serialization/deserialization processes.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Example
&lt;/h2&gt;

&lt;p&gt;Suppose you have a Node.js server application that handles various API routes, and you want to measure the execution time of certain methods to monitor performance. You can use decorators to create a reusable method timing decorator that logs the execution time of methods. Here’s an example implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 👇 Decorator to measure method execution time
function measureTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = async function (...args: any[]) {
    const start = Date.now();
    const result = await originalMethod.apply(this, args);
    const end = Date.now();
    const executionTime = end - start;

    console.log(`${propertyKey} took ${executionTime}ms`);

    return result;
  };

  return descriptor;
}

class UserController {
  // 👇 Add metadata like this 
  @measureTime
  static async getUser(userId: string) {
    await new Promise((resolve) =&amp;gt; setTimeout(resolve, 2000));
    return { id: userId, name: 'John Doe' };
  }
}

// Express route handler
app.get('/users/:id', async (req, res) =&amp;gt; {
  const userId = req.params.id;
  const user = await UserController.getUser(userId);
  res.json(user);
});

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

&lt;/div&gt;



&lt;p&gt;I have only scratched the surface of decorators in TypeScript with a few mentioned use cases, but there’s so much more to explore! Feel free to dive into the rich functionality of TypeScript and expand your toolkit. Today, I have equipped you with a valuable addition to your TypeScript toolbox.&lt;/p&gt;

&lt;p&gt;I genuinely believe this article will be a helpful resource for all of you!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; keep coding!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>react</category>
      <category>typescript</category>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>TypeScript Explained: Type and Interface</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Mon, 03 Jul 2023 19:17:53 +0000</pubDate>
      <link>https://dev.to/arulvalananto/typescript-explained-type-and-interface-3aom</link>
      <guid>https://dev.to/arulvalananto/typescript-explained-type-and-interface-3aom</guid>
      <description>&lt;p&gt;In this article, We will dive deep into the differences between ‘type’ and ‘interfaces’ in TypeScript, along with their advantages and disadvantages. Let’s get started!&lt;/p&gt;

&lt;h2&gt;
  
  
  Type
&lt;/h2&gt;

&lt;p&gt;In typescript, the type keyword is used to create custom type definitions. It allows you to define a new type by specifying the structure, constraints, and composition of the values it can hold.&lt;/p&gt;

&lt;h3&gt;
  
  
  When to use
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Defining Union or Intersection Types: When you need to create a type that can hold multiple types, such as a variable that can be either a number or a string, you can use &lt;code&gt;type&lt;/code&gt; to define a union type:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type size = 'small' | 'medium' | 'large';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Creating Complex Type Combinations: If you need to combine multiple types to create a more complex type, such as combining properties from different types.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Human = {
  name: string;
  age: number;
}

type Power = string;

type SuperHuman = Human &amp;amp; Power;

const batman: SuperHuman = {
  name: 'Batman',
  age: 32,
  power: 'wealth'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Creating Aliases for Existing Types: When you want to give a more meaningful name to an existing type, you can use &lt;code&gt;type&lt;/code&gt; to create an alias:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type customerId = number;
type customerAge = number;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Documenting Function Signatures: If you have a function with a complex signature or multiple parameter types, using &lt;code&gt;type&lt;/code&gt; can provide clarity and improve code readability:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type SendMessage = (message: string, recipient: string) =&amp;gt; void;

const sendMailToRecipient: sendMessage = (message, recipient) =&amp;gt; {
  console.log(`Message sent to ${recipient}!`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Pros
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;It allows you to create complex type combinations easily.&lt;/li&gt;
&lt;li&gt;It provides flexibility in combining different types.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Cons
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;It cannot be implemented or extended by classes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Interface
&lt;/h2&gt;

&lt;p&gt;In TypeScript, an interface is a way to define a structure of an object. It allows you to specify the properties, methods, and types that an object must have to adhere to the defined interface.&lt;/p&gt;

&lt;h3&gt;
  
  
  When to use
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Defining Object structure: When you want to specify the structure and shape of an object, interfaces provide a clean and intuitive way to define its properties and their types:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Person {
  name: string;
  age: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Describing Class Contracts: If you are working with classes and want to define a contract that specifies certain properties or methods that must be implemented, interfaces are a natural choice:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Printable {
  print(): void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Extending Interfaces: Interfaces can be extended to inherit properties and methods from other interfaces, facilitating code reuse and promoting modularity:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Car {
  brand: string;
  model: string;
  start(): void;
  stop(): void;
}

interface ElectricCar extends Car {
  batteryCapacity: number;
  charge(): void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Implementing Interfaces: Classes can implement interfaces, ensuring they adhere to a specific contract and providing a way to enforce consistency across multiple classes:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Tesla implements ElectricCar {
  brand: string;
  model: string;
  batteryCapacity: number;

  constructor(brand: string, model: string, batteryCapacity: number) {
    this.brand = brand;
    this.model = model;
    this.batteryCapacity = batteryCapacity;
  }

  start() {
    console.log(`Starting the ${this.brand} ${this.model} electric car.`);
  }

  stop() {
    console.log(`Stopping the ${this.brand} ${this.model} electric car.`);
  }

  charge() {
    console.log(`Charging the ${this.brand} ${this.model} electric car.`);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Pros
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;It provides a clear and concise syntax for defining object shapes and class contracts.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It supports inheritance and allows for extending or implementing interfaces.&lt;/p&gt;
&lt;h3&gt;
  
  
  Cons
&lt;/h3&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It cannot represent union or intersection types directly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It might not be as flexible for defining complex type combinations as ‘type’.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In conclusion, understanding when to use ‘type’ and ‘interface’ for custom type definitions in TypeScript is crucial for writing clean and maintainable code. Both ‘type’ and ‘interface’ serve similar purposes but have distinct features and use cases. With this understanding, you can use TypeScript and make informed decisions when choosing between ‘type’ and ‘interface’ for your custom type definitions.&lt;/p&gt;

&lt;p&gt;I hope you find this article valuable!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; keep coding!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>typescript</category>
      <category>interface</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Introduce you: Highlight</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Mon, 03 Jul 2023 11:11:17 +0000</pubDate>
      <link>https://dev.to/arulvalananto/introduce-you-highlight-2nn8</link>
      <guid>https://dev.to/arulvalananto/introduce-you-highlight-2nn8</guid>
      <description>&lt;p&gt;A code snippet highlighter tool for bloggers, developers, and designers! In this article, I am going to cover the features of Highlight, a platform that allows bloggers, developers, and designers to create visually stunning and attention-grabbing code snippets with a few clicks. Let’s explore its features.&lt;/p&gt;

&lt;h2&gt;
  
  
  Customize and Capture
&lt;/h2&gt;

&lt;p&gt;Highlight offers the ability to customize and adjust code blocks, allowing you to fine-tune your design to perfection and ensure that your code appears optimal on any device or platform. With resizable and adjustable code blocks, you can change your code’s appearance.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rW6pRIu3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gg4nanr8g5vg3hcfx3io.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rW6pRIu3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gg4nanr8g5vg3hcfx3io.png" alt="Customization with Highlight" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When your design is finished, effortlessly capture a visually enhanced image of your code snippet with a simple click of the capture button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K64YrebX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhn0enjwast3mc4w9o7o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K64YrebX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nhn0enjwast3mc4w9o7o.png" alt="Capture as an image with a different file format" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Offline and Easy to Install
&lt;/h2&gt;

&lt;p&gt;Highlight comes with offline functionality, allowing you to work on your stunning code snippets without an internet connection, and its easy-to-install plugin features make integrating Highlight into your workflow a breeze. You’ll find it conveniently located in the top-right corner of your search box.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tObeWwPu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmnp1zkw562my7f1qe5a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tObeWwPu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmnp1zkw562my7f1qe5a.png" alt="Install Highlight app" width="800" height="433"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Embedded Link
&lt;/h2&gt;

&lt;p&gt;With Hightlight’s embedded link feature, you can effortlessly place your visually enhanced code snippet inside your blog or project and make your blog posts or websites shine with the brilliance of your code! To create an embedded link, simply click on the embedded link button at the top right of the Highlight app.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zOLVB5T_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d15ufkdz9zazfac5s375.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zOLVB5T_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d15ufkdz9zazfac5s375.png" alt="Create an Embedded Link with Highlight" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you generate the embedded link, you can seamlessly incorporate it into your blogs or websites using iframe. The embedded link is created based on the design settings you had at the time you clicked the ‘copy link’ button. You can further customize its behavior using parameters. For example, you can adjust the default width by adding ‘w’ in the URL, like this: Your_hightlight_url?w=100&lt;/p&gt;

&lt;p&gt;In this example, I have set the width to 100 pixels (the default unit of measurement). Additionally, you have the flexibility to modify the height(h), border radius(b), font size(f), and background color(bg). Use hex code without # for the background color.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JOLLu8FI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwxt18l8wnkk9fk7x8qp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JOLLu8FI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwxt18l8wnkk9fk7x8qp.png" alt="Customize Embedded Link with URL Parameters" width="800" height="403"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Share this exciting platform with your friends and colleagues who crave the same visual brilliance in their code.&lt;/p&gt;

&lt;p&gt;Head over at &lt;a href="https://highlightt.web.app/"&gt;Highlight&lt;/a&gt; and Get started now 🚀.&lt;/p&gt;

&lt;p&gt;I hope this article is useful to you!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; keep coding&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>tooling</category>
      <category>code</category>
      <category>design</category>
    </item>
    <item>
      <title>5 Advanced NodeJS Techniques</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Sun, 02 Jul 2023 12:00:55 +0000</pubDate>
      <link>https://dev.to/arulvalananto/5-advanced-nodejs-techniques-20k6</link>
      <guid>https://dev.to/arulvalananto/5-advanced-nodejs-techniques-20k6</guid>
      <description>&lt;p&gt;As developers, we all strive for efficient and robust codebases that are easy to understand, modify, and extend. By adopting best practices and exploring advanced techniques, we can unlock the true potential of NodeJS and significantly improve the quality of our applications. In this blog, we will focus on five advanced techniques of NodeJS. So, fasten your seatbelts and get ready to explore them.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Add Middleware
&lt;/h2&gt;

&lt;p&gt;Instead of adding the middleware to each route, add it at the top of the route list using the use method. This way, any routes defined below the middleware will automatically go through the middleware before reaching their respective route handlers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const route = express.Router();
const {login} = require("../controllers/auth");

route.get('/login', login)

// isAuthenticated is middleware that checks whether 
// you are authenticated or not
// // ❌ Avoid this: middleware on each route
route.get('/products', isAuthenticated, fetchAllProducts);
route.get('/product/:id', isAuthenticated, getProductById)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ✅ Instead, do this
// Route without middleware
route.get('/login', login)

// Middleware function: isAuthenticated
// This will be applied to all routes defined after this point
route.use(isAuthenticated);

// Routes that will automatically check the middleware
route.get('/products', fetchAllProducts);
route.get('/product/:id', getProductById);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach helps keep the code organized and avoids repeating the middleware for each route individually.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Use Global Error Handling
&lt;/h2&gt;

&lt;p&gt;Instead of structuring the error response on every controller, we can use NodeJS Global error-handling feature. First, Create a custom AppError class derived from the built-in Error class. This custom class allows you to customize the error object with additional properties like statusCode and status.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Custom Error class
module.exports = class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    this.status = statusCode &amp;lt; 500 ? "error" : "fail";

    Error.captureStackTrace(this, this.constructor);
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you have created a Custom Error class, add a global error handler middleware inside your root router file. This middleware function takes four parameters (err, req, res, next) and handles errors throughout the application. Inside the global error handler, you format the error response based on the error object’s statusCode, status, and message properties. You can customize this response format to suit your needs. Additionally, the stack property is included for development environments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Express setup
const express = require('express');

const app = express();

app.use('/', (req, res) =&amp;gt; {
  res.status(200).json({ message: "it works" });
});

app.use('*', (req, res) =&amp;gt; {
    res.status(404).json({
        message: `Can't find ${req.originalUrl} this route`,
    });
});

// 👇 add a global error handler after all the routes.
app.use((err, req, res, next) =&amp;gt; {
  err.status = err.status || "fail";
  err.statusCode = err.statusCode || 500;

  res.status(err.statusCode).json({
    status: err.status,
    message: transformMessage(err.message),
    stack: process.env.NODE_ENV === "development" ? err.stack : undefined,
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After you’ve added it, you can throw an error using next(new AppError(message, statusCode)). The next function automatically passes the error to the global error handler middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// inside controllers

// route.get('/login', login);

exports.login = async (req, res, next) =&amp;gt; {
  try {
    const { email, password } = req.body;

    const user = await User.findOne({ email }).select("+password +lastLoginAt");

    if (!user || !(await user.correctPassword(password, user.password))) {
      // 👇 like this
      return next(new AppError("Invalid Email / Password / Method", 404));
    }

     // Custom logic for generating a token
    const token = 'generated_token';

    res.status(200).json({ token });
  } catch(error) {
      next(error
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Overall, this approach simplifies error handling by centralizing it in one place, making it easier to maintain and customize error responses across your application.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Use Custom Try-Catch Function
&lt;/h2&gt;

&lt;p&gt;Instead of manually wrapping each controller function with a try-catch block, we can use a customized function that achieves the same purpose.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ❌ Avoid this
// Using try-catch block each controllers
exports.login = async (req, res, next) =&amp;gt; {
  try {
    // logic here
  } catch(error) {
      res.status(400).json({ message: 'You error message'}
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The tryCatchFn function accepts a function (fn) as input and returns a new function that wraps the original function with a try-catch block. If an error occurs within the wrapped function, it is caught using the catch method, and the error is passed to the next function to be handled by the Global error handler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ✅ Instead, do this
const tryCatchFn = (fn) =&amp;gt; {
  return (req, res, next) =&amp;gt; {
    fn(req, res, next).catch(next);
  };
}

// To use this custom function, you can wrap your controller 
// functions with tryCatchFn:
exports.login = tryCatchFn(async (req, res, next) =&amp;gt; {
  // logic here
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By wrapping your controller functions with tryCatchFn, you ensure that any errors thrown within those functions will be automatically caught and passed to the global error handler, eliminating the need to add try-catch blocks individually.&lt;/p&gt;

&lt;p&gt;This approach helps to centralize error handling in a cleaner and more concise way, making your code more maintainable and reducing repetitive error handling code.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Separate the Main file into two parts.
&lt;/h2&gt;

&lt;p&gt;When developing a NodeJS application using Express, it is common to have a main file that contains all the business logic, route definitions, and server setup. However, managing and maintaining a single file that handles everything can become difficult as the application grows.&lt;/p&gt;

&lt;p&gt;One recommended technique to address this issue and keep the codebase cleaner and more organized is to separate the main file into two parts: one for routes and another for server setup or configuration. Here’s an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// app.js
const express = require('express');
const app = express();

/* Middlewares */

app.get('/', (req, res) =&amp;gt; {
  res.status(200).json({ message: "it works" });
})

app.use(/* Global Error Handler */);
module.exports = app;

// server.js
const app = require('./app');
const port = process.env.PORT || 5001;

app.listen(port, () =&amp;gt; console.log('Server running at', port));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Separate routes from controllers
&lt;/h2&gt;

&lt;p&gt;To achieve a more organized and modular codebase, I recommended separating routes from controllers. This practice helps to maintain a clear separation of concerns and improves code readability and maintainability. Here’s an example that demonstrates the separation of routes and controllers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ❌ Avoid this
const route = express.Router();

route.get('/login', tryCatchFn(req, res, next) =&amp;gt; {
  // logic here
}))

// ✅ Do this
const route = express.Router();
const {login} = require("../controllers/auth");

route.get('/login', login);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;In this article, we have discussed different advanced techniques to write NodeJS code that is clean and easy to maintain. There are many best practices available that can significantly improve the quality of your application’s code. Feel free to explore these techniques and apply them to enhance your codebase.&lt;/p&gt;

&lt;p&gt;I hope you find this article enjoyable.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; keep coding!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>node</category>
      <category>cleancode</category>
    </item>
    <item>
      <title>Debounce vs. Throttle: Decoding the Duel</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Sat, 01 Jul 2023 17:05:55 +0000</pubDate>
      <link>https://dev.to/arulvalananto/debounce-vs-throttle-decoding-the-duel-2b9c</link>
      <guid>https://dev.to/arulvalananto/debounce-vs-throttle-decoding-the-duel-2b9c</guid>
      <description>&lt;p&gt;As developers, we always strive to improve the performance of our applications. Two techniques that can significantly enhance web application performance are debouncing and throttling. In this article, we will explore these techniques, understand their differences, and see how they can be effectively used. So without wasting any time, let’s dive in and explore these techniques with examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  Debouncing
&lt;/h2&gt;

&lt;p&gt;Debouncing is a technique that limits the frequency of function calls within a specified timeframe. By preventing rapid execution of a specific function, debouncing enhances performance in situations where the function is triggered frequently, such as user input events like keystrokes, window resizing, or scroll events. Let’s delve into the specific problem and explore how debouncing can be applied to solve it effectively.&lt;/p&gt;

&lt;h3&gt;
  
  
  Actual Problem
&lt;/h3&gt;

&lt;p&gt;Consider a situation we have an e-commerce website where we have a search box with an input field that triggers a search function every time the user types a character. Without debouncing, the search function would be called with each keystroke, potentially overloading the server and impacting the application’s responsiveness and overall performance.&lt;/p&gt;

&lt;h3&gt;
  
  
  Solution
&lt;/h3&gt;

&lt;p&gt;We can wrap the search function with debouncing function to address this issue. Let’s see this with an example.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Javascript&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const input = document.querySelector(".custom-input");

// ❌ Before implementation
const searchResults = (event) =&amp;gt; {
  // Your core logic will be here!
  console.log(event.target.value);
};

if (input) {
  // Triggers for each keystrokes
  input.addEventListener("input", searchResults);
}

// ✅ After implementation
const debounce = (cb, delay) =&amp;gt; {
  let debounceTime;

  return (...args) =&amp;gt; {
    clearTimeout(debounceTime);
    debounceTime = setTimeout(() =&amp;gt; {
      cb(...args);
    }, delay);
  };
};

if (input) {
  // being debounced with a delay of 500 milliseconds
  input.addEventListener("input", debounce(searchResults, 500));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reference: &lt;a href="https://codesandbox.io/s/debounce-with-js-jjc9yx"&gt;https://codesandbox.io/s/debounce-with-js-jjc9yx&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;React&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Here, we implemented debouncing with React new hook called `useDeferredValue.`
export default function App() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);

  return (
    &amp;lt;&amp;gt;
      &amp;lt;label&amp;gt;
        Search albums:
        &amp;lt;input value={query} onChange={e =&amp;gt; setQuery(e.target.value)} /&amp;gt;
      &amp;lt;/label&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;Reference: &lt;a href="https://react.dev/reference/react/useDeferredValue#usedeferredvalue"&gt;https://react.dev/reference/react/useDeferredValue#usedeferredvalue&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Throttling
&lt;/h2&gt;

&lt;p&gt;Throttling is a technique that controls function execution rate for a specific timeframe. It restricts the frequency of function executions by adding a minimum time interval between consecutive calls. It helps regulate the execution rate and prevent excessive function calls, ensuring optimal performance and resource utilization. Now, let’s explore a specific problem and demonstrate how throttling can be used to address it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Actual Problem
&lt;/h3&gt;

&lt;p&gt;When a user resizes the window, the resize event fires continuously, triggering expensive operations such as recalculating layouts or re-rendering elements. These operations can overwhelm the browser without throttling and lead to a sluggish user experience.&lt;/p&gt;

&lt;h3&gt;
  
  
  Solution
&lt;/h3&gt;

&lt;p&gt;Throttling the window resize event ensures that the expensive operations are executed at a controlled rate, preventing excessive function invocations and optimizing performance.&lt;/p&gt;

&lt;p&gt;Here’s an example:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Javascript&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const height = document.querySelector("#height");
const width = document.querySelector("#width");

// ❌ Before implementation
// invokes for each change
const handleResize = () =&amp;gt; {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
  // Your business logic over here
};

(() =&amp;gt; {
  handleResize();
})();

window.addEventListener("resize", handleResize);

// ✅ After implementation
// invoke only once every 500 milliseconds (given delay)

const throttle = (cb, delay) =&amp;gt; {
  let throttling = false;

  return (...args) =&amp;gt; {
    if (!throttling) {
      throttling = true;

      cb(...args);

      setTimeout(() =&amp;gt; {
        throttling = false;
      }, delay);
    }
  };
};

window.addEventListener("resize", throttle(handleResize, 500));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reference: &lt;a href="https://codesandbox.io/s/throttle-in-js-4zkk5j"&gt;https://codesandbox.io/s/throttle-in-js-4zkk5j&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;React&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useRef } from "react";

export default function App() {
  const heightRef = useRef();
  const widthRef = useRef();

  const throttle = (cb, delay) =&amp;gt; {
    let throttling = false;

    return (...args) =&amp;gt; {
      if (!throttling) {
        throttling = true;

        cb(...args);

        setTimeout(() =&amp;gt; {
          throttling = false;
        }, delay);
      }
    };
  };

  useEffect(() =&amp;gt; {
    const handleResize = () =&amp;gt; {
      heightRef.current.textContent = window.innerHeight;
      widthRef.current.textContent = window.innerWidth;
      // Your business logic over here
    };
    window.addEventListener("resize", throttle(handleResize, 500));

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

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;
        Current window width: &amp;lt;span ref={widthRef}&amp;gt;&amp;lt;/span&amp;gt;
      &amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;
        Current window height: &amp;lt;span ref={heightRef}&amp;gt;&amp;lt;/span&amp;gt;
      &amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reference: &lt;a href="https://codesandbox.io/s/throttling-with-reactjs-gxqyx4"&gt;https://codesandbox.io/s/throttling-with-reactjs-gxqyx4)&lt;/a&gt;&lt;/p&gt;

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

&lt;p&gt;Both throttle and debounce are valuable techniques in JavaScript for managing the frequency of function invocations. While they serve similar purposes of optimizing performance and controlling execution rates, they differ in handling consecutive function calls.&lt;/p&gt;

&lt;p&gt;Throttling ensures a function is executed at a controlled rate by enforcing a minimum interval between consecutive calls. Debouncing, on the other hand, delays the execution of a function until there is a pause or inactivity in function calls for a specified period.&lt;/p&gt;

&lt;p&gt;Both techniques help optimize performance, reduce unnecessary computations, and improve user experience by controlling the frequency of function executions. Understanding their differences and choosing the right technique based on your use case will enable you to design more efficient and responsive JavaScript applications.&lt;/p&gt;

&lt;p&gt;I hope this article is helpful to you!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; keep coding!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>performance</category>
      <category>optimization</category>
    </item>
    <item>
      <title>Mastering SOLID Principles in Just 8 Minutes!</title>
      <dc:creator>Arul Valan Anto S</dc:creator>
      <pubDate>Sun, 18 Jun 2023 16:55:36 +0000</pubDate>
      <link>https://dev.to/arulvalananto/mastering-solid-principles-in-just-8-minutes-3c5b</link>
      <guid>https://dev.to/arulvalananto/mastering-solid-principles-in-just-8-minutes-3c5b</guid>
      <description>&lt;p&gt;In this blog, I will demonstrate the implementation of SOLID principles in a React application. By the end of this article, you will fully grasp SOLID principles. Before we begin, let me give you a brief introduction to those principles.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are SOLID principles?
&lt;/h2&gt;

&lt;p&gt;SOLID principles are five design principles that help us keep our application reusable, maintainable, scalable, and loosely coupled. The SOLID principles are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Single-responsibility principle&lt;/li&gt;
&lt;li&gt;Open-Closed principle&lt;/li&gt;
&lt;li&gt;Liskov substitution principle&lt;/li&gt;
&lt;li&gt;Interface segregation principle&lt;/li&gt;
&lt;li&gt;Dependency inversion principle&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Okay, let’s examine each of these principles individually. I use React as an example, but the core concepts are similar to other programming languages and frameworks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Single-responsibility Principle
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;“A module should be responsible to one, and only one, actor.” — Wikipedia.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Single Responsibility Principle states that a component should have one clear purpose or responsibility. It should focus on specific functionality or behavior and avoid taking on unrelated tasks. Following SRP makes components more focused, modular, and easily comprehended and modified. Let’s see the actual implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ❌ Bad Practice: Component with Multiple Responsibilities

const Products = () =&amp;gt; {
    return (
        &amp;lt;div className="products"&amp;gt;
            {products.map((product) =&amp;gt; (
                &amp;lt;div key={product?.id} className="product"&amp;gt;
                    &amp;lt;h3&amp;gt;{product?.name}&amp;lt;/h3&amp;gt;
                    &amp;lt;p&amp;gt;${product?.price}&amp;lt;/p&amp;gt;
                &amp;lt;/div&amp;gt;
            ))}
        &amp;lt;/div&amp;gt;
    );
};

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

&lt;/div&gt;



&lt;p&gt;In the above example, the Products component violates the Single Responsibility Principle by taking on multiple responsibilities. It manages the iteration of products and handles the UI rendering for each product. This can make the component challenging to understand, maintain, and test in the future.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instead, do this to adhere to SRP:&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;// ✅ Good Practice: Separating Responsibilities into Smaller Components

import Product from './Product';
import products from '../../data/products.json';

const Products = () =&amp;gt; {
    return (
        &amp;lt;div className="products"&amp;gt;
            {products.map((product) =&amp;gt; (
                &amp;lt;Product key={product?.id} product={product} /&amp;gt;
            ))}
        &amp;lt;/div&amp;gt;
    );
};

// Product.js
// Separate component responsible for rendering the product details
const Product = ({ product }) =&amp;gt; {
    return (
        &amp;lt;div className="product"&amp;gt;
            &amp;lt;h3&amp;gt;{product?.name}&amp;lt;/h3&amp;gt;
            &amp;lt;p&amp;gt;${product?.price}&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
    );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This separation ensures each component has a single responsibility, making them easier to understand, test, and maintain.&lt;/p&gt;

&lt;h2&gt;
  
  
  Open-Closed Principle
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;“software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” — Wikipedia.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Open-Closed Principle emphasizes that components should be open for extension (can add new behaviors or functionalities) but closed for modification(existing code should remain unchanged). This principle encourages the creation of code that is resilient to change, modular, and easily maintainable. Let’s see the actual implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ❌ Bad Practice: Violating the Open-Closed Principle

// Button.js
// Existing Button component
const Button = ({ text, onClick }) =&amp;gt; {
  return (
    &amp;lt;button onClick={onClick}&amp;gt;
      {text}
    &amp;lt;/button&amp;gt;
  );
}

// Button.js
// Modified Existing Button component with additional icon prop (modification)
const Button = ({ text, onClick, icon }) =&amp;gt; {
  return (
    &amp;lt;button onClick={onClick}&amp;gt;
      &amp;lt;i className={icon} /&amp;gt;
      &amp;lt;span&amp;gt;{text}&amp;lt;/span&amp;gt;
    &amp;lt;/button&amp;gt;
  );
}

// Home.js
// 👇 Avoid: Modified existing component prop
const Home = () =&amp;gt; {
  const handleClick= () =&amp;gt; {};

  return (
    &amp;lt;div&amp;gt;
      {/* ❌ Avoid this */}
      &amp;lt;Button text="Submit" onClick={handleClick} icon="fas fa-arrow-right" /&amp;gt; 
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we modify the existing Button component by adding an icon prop. Altering an existing component to accommodate new requirements violates the Open-Closed Principle. These changes make the component more fragile and introduce the risk of unintended side effects when used in different contexts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instead, Do this:&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;// ✅ Good Practice: Open-Closed Principle

// Button.js
// Existing Button functional component
const Button = ({ text, onClick }) =&amp;gt; {
  return (
    &amp;lt;button onClick={onClick}&amp;gt;
      {text}
    &amp;lt;/button&amp;gt;
  );
}

// IconButton.js
// IconButton component
// ✅ Good: You have not modified anything here.
const IconButton = ({ text, icon, onClick }) =&amp;gt; {
  return (
    &amp;lt;button onClick={onClick}&amp;gt;
      &amp;lt;i className={icon} /&amp;gt;
      &amp;lt;span&amp;gt;{text}&amp;lt;/span&amp;gt;
    &amp;lt;/button&amp;gt;
  );
}

const Home = () =&amp;gt; {
  const handleClick = () =&amp;gt; {
    // Handle button click event
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Button text="Submit" onClick={handleClick} /&amp;gt;
      {/* 
      &amp;lt;IconButton text="Submit" icon="fas fa-heart" onClick={handleClick} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we create a separate IconButton functional component. The IconButton component encapsulates the rendering of an icon button without modifying the existing Button component. It adheres to the Open-Closed Principle by extending the functionality through composition rather than modification.&lt;/p&gt;

&lt;h2&gt;
  
  
  Liskov Substitution Principle
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;“Subtype objects should be substitutable for supertype objects” — Wikipedia.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Liskov Substitution Principle (LSP) is a fundamental principle of object-oriented programming that emphasizes the need for substitutability of objects within a hierarchy. In the context of React components, LSP promotes the idea that derived components should be able to substitute their base components without affecting the correctness or behavior of the application. Let’s see the actual implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ⚠️ Bad Practice
// This approach violates the Liskov Substitution Principle as it modifies 
// the behavior of the derived component, potentially resulting in unforeseen 
// problems when substituting it for the base Select component.
const BadCustomSelect = ({ value, iconClassName, handleChange }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;i className={iconClassName}&amp;gt;&amp;lt;/i&amp;gt;
      &amp;lt;select value={value} onChange={handleChange}&amp;gt;
        &amp;lt;options value={1}&amp;gt;One&amp;lt;/options&amp;gt;
        &amp;lt;options value={2}&amp;gt;Two&amp;lt;/options&amp;gt;
        &amp;lt;options value={3}&amp;gt;Three&amp;lt;/options&amp;gt;
      &amp;lt;/select&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const LiskovSubstitutionPrinciple = () =&amp;gt; {
  const [value, setValue] = useState(1);

  const handleChange = (event) =&amp;gt; {
    setValue(event.target.value);
  };

  return (
    &amp;lt;div&amp;gt;
      {/** ❌ Avoid this */}
      {/** Below Custom Select doesn't have the characteristics of base `select` element */}
      &amp;lt;BadCustomSelect value={value} handleChange={handleChange} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we have a BadCustomSelect component intended to serve as a custom select input in React. However, it violates the Liskov Substitution Principle (LSP) because it restricts the behavior of the base select element.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instead, Do this:&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;// ✅ Good Practice
// This component follows the Liskov Substitution Principle and allows the use of select's characteristics.

const CustomSelect = ({ value, iconClassName, handleChange, ...props }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;i className={iconClassName}&amp;gt;&amp;lt;/i&amp;gt;
      &amp;lt;select value={value} onChange={handleChange} {...props}&amp;gt;
        &amp;lt;options value={1}&amp;gt;One&amp;lt;/options&amp;gt;
        &amp;lt;options value={2}&amp;gt;Two&amp;lt;/options&amp;gt;
        &amp;lt;options value={3}&amp;gt;Three&amp;lt;/options&amp;gt;
      &amp;lt;/select&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const LiskovSubstitutionPrinciple = () =&amp;gt; {
  const [value, setValue] = useState(1);

  const handleChange = (event) =&amp;gt; {
    setValue(event.target.value);
  };

  return (
    &amp;lt;div&amp;gt;
      {/* ✅ This CustomSelect component follows the Liskov Substitution Principle */}
      &amp;lt;CustomSelect
        value={value}
        handleChange={handleChange}
        defaultValue={1}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the revised code, we have a CustomSelect component intended to extend the functionality of the standard select element in React. The component accepts props such as value, iconClassName, handleChange, and additional props using the spread operator ...props. By allowing the use of the select element's characteristics and accepting additional props, the CustomSelect component follows the Liskov Substitution Principle (LSP).&lt;/p&gt;

&lt;h2&gt;
  
  
  Interface Segregation Principle
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;“No code should be forced to depend on methods it does not use.” — Wikipedia.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Interface Segregation Principle (ISP) suggests that interfaces should be focused and tailored to specific client requirements rather than being overly broad and forcing clients to implement unnecessary functionality. Let’s see the actual implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ❌ Avoid: disclose unnecessary information for this component
// This introduces unnecessary dependencies and complexity for the component
const ProductThumbnailURL = ({ product }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;img src={product.imageURL} alt={product.name} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

// ❌ Bad Practice
const Products = ({ product }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ProductThumbnailURL product={product} /&amp;gt;
      &amp;lt;h4&amp;gt;{product?.name}&amp;lt;/h4&amp;gt;
      &amp;lt;p&amp;gt;{product?.description}&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;{product?.price}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const Products = () =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      {products.map((product) =&amp;gt; (
        &amp;lt;Product key={product.id} product={product} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we pass the entire product details to the ProductThumbnailURL component, even though it doesn’t require it. It adds unnecessary risks and complexity to the component and violates the Interface Segregation Principle (ISP).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let’s refactor to adhere to ISP:&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;// ✅ Good: reducing unnecessary dependencies and making 
// the codebase more maintainable and scalable.
const ProductThumbnailURL = ({ imageURL, alt }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;img src={imageURL} alt={alt} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
// ✅ Good Practice
const Products = ({ product }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ProductThumbnailURL imageURL={product.imageURL} alt={product.name} /&amp;gt;
      &amp;lt;h4&amp;gt;{product?.name}&amp;lt;/h4&amp;gt;
      &amp;lt;p&amp;gt;{product?.description}&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;{product?.price}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
const Products = () =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      {products.map((product) =&amp;gt; (
        &amp;lt;Product key={product.id} product={product} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the revised code, the ProductThumbnailURL component only receives the required information instead of the entire product details. It prevents unnecessary risks and fosters the Interface Segregation Principle (ISP).&lt;/p&gt;

&lt;h2&gt;
  
  
  Dependency Inversion Principle
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;“One entity should depend upon abstractions, not concretions” — Wikipedia.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Dependency Inversion Principle (DIP) emphasizes that high-level components should not depend on low-level components. This principle fosters loose coupling and modularity and facilitates easier maintenance of software systems. Let’s see the actual implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ❌ Bad Practice
// This component follows concretion instead of abstraction and 
// breaks Dependency Inversion Principle

const CustomForm = ({ children }) =&amp;gt; {
  const handleSubmit = () =&amp;gt; {
    // submit operations
  };
  return &amp;lt;form onSubmit={handleSubmit}&amp;gt;{children}&amp;lt;/form&amp;gt;;
};

const DependencyInversionPrinciple = () =&amp;gt; {
  const [email, setEmail] = useState();

  const handleChange = (event) =&amp;gt; {
    setEmail(event.target.value);
  };

  const handleFormSubmit = (event) =&amp;gt; {
    // submit business logic here
  };

  return (
    &amp;lt;div&amp;gt;
      {/** ❌ Avoid: tightly coupled and hard to change */}
      &amp;lt;BadCustomForm&amp;gt;
        &amp;lt;input
          type="email"
          value={email}
          onChange={handleChange}
          name="email"
        /&amp;gt;
      &amp;lt;/BadCustomForm&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The CustomForm component is tightly coupled to its children, preventing flexibility and making it challenging to change or extend its behavior.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instead, Do this:&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;// ✅ Good Practice
// This component follows abstraction and promotes Dependency Inversion Principle

const AbstractForm = ({ children, onSubmit }) =&amp;gt; {
  const handleSubmit = (event) =&amp;gt; {
    event.preventDefault();
    onSubmit();
  };

  return &amp;lt;form onSubmit={handleSubmit}&amp;gt;{children}&amp;lt;/form&amp;gt;;
};

const DependencyInversionPrinciple = () =&amp;gt; {
  const [email, setEmail] = useState();

  const handleChange = (event) =&amp;gt; {
    setEmail(event.target.value);
  };

  const handleFormSubmit = () =&amp;gt; {
    // submit business logic here
  };

  return (
    &amp;lt;div&amp;gt;
      {/** ✅ Use the abstraction instead */}
      &amp;lt;AbstractForm onSubmit={handleFormSubmit}&amp;gt;
        &amp;lt;input
          type="email"
          value={email}
          onChange={handleChange}
          name="email"
        /&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
      &amp;lt;/AbstractForm&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the revised code, we introduce the AbstractForm component, which acts as an abstraction for the form. It receives the onSubmit function as a prop and handles the form submission. This approach allows us to easily swap out or extend the form behavior without modifying the higher-level component.&lt;/p&gt;

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

&lt;p&gt;The SOLID principles provide guidelines that empower developers to create well-designed, maintainable, and extensible software solutions. By adhering to these principles, developers can achieve modularity, code reusability, flexibility, and reduced code complexity.&lt;/p&gt;

&lt;p&gt;I hope this blog has provided valuable insights and inspired you to apply these principles in your existing or following React projects.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Stay curious; keep coding!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Reference: &lt;a href="https://codesandbox.io/s/solid-principles-react-o4hn5s"&gt;https://codesandbox.io/s/solid-principles-react-o4hn5s&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>performance</category>
      <category>design</category>
      <category>designpatterns</category>
    </item>
  </channel>
</rss>
