<?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: padmajothi Athimoolam</title>
    <description>The latest articles on DEV Community by padmajothi Athimoolam (@padmajothi_athimoolam_23d).</description>
    <link>https://dev.to/padmajothi_athimoolam_23d</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%2F1988938%2Faf65ed83-012b-4b80-b797-e20d0c7b3415.png</url>
      <title>DEV Community: padmajothi Athimoolam</title>
      <link>https://dev.to/padmajothi_athimoolam_23d</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/padmajothi_athimoolam_23d"/>
    <language>en</language>
    <item>
      <title>Enforcing Immutability in Singleton Pattern with Object.freeze()</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Wed, 29 Jan 2025 18:05:43 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/enforcing-immutability-in-singleton-pattern-with-objectfreeze-kn3</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/enforcing-immutability-in-singleton-pattern-with-objectfreeze-kn3</guid>
      <description>&lt;p&gt;Using Object.freeze() in a Singleton design pattern ensures that the singleton instance cannot be modified once it has been created. This can be useful when you want to prevent changes to the Singleton instance, making sure it remains immutable and its properties are protected from being altered after initialization.&lt;/p&gt;

&lt;p&gt;Example: Using Object.freeze() in a Singleton Pattern&lt;br&gt;
Here’s how you can implement the Singleton pattern with Object.freeze():&lt;/p&gt;

&lt;p&gt;** Singleton Design Pattern with Object.freeze()**&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ThemeManager {
    constructor() {
        if(ThemeManager.instance) {
            this.theme = localStorage.getItem('theme') || 'light';
            ThemeManager.instance = this;
        }

        return ThemeManager.instance;
    }

    setTheme(newTheme) {
        this.theme = newTheme;
        localStorage.setItem('theme', newTheme);
    }

    getTheme() {
        return this.theme
    }
 }

 const themeManager = new ThemeManager(); // Create an instance
 Object.freeze(this); // Freeze the instance to make it immutable
 export default themeManager; // Export the instance
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Object.freeze(): The Object.freeze(this) call makes the instance immutable after it's created, meaning you cannot add new properties, modify existing properties, or change the state of the themeManager instance.If you try to modify themeManager after freezing, it won't allow changes, providing a layer of protection.It will throw error &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Uncaught TypeError: Cannot add property theme, object is not extensible&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Why Use Object.freeze()?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Immutability:&lt;/em&gt; Once an instance is created, it can't be modified. This is particularly useful when you want to prevent accidental changes to the Singleton object’s properties and methods.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Enforce Consistency:&lt;/em&gt; You ensure that the Singleton instance is always consistent and protected against any changes that might break the application logic.&lt;/p&gt;

</description>
      <category>singleton</category>
      <category>immutability</category>
      <category>freeze</category>
      <category>themes</category>
    </item>
    <item>
      <title>What is the Singleton Pattern?</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Wed, 29 Jan 2025 17:52:34 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/what-is-the-singleton-pattern-5e6g</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/what-is-the-singleton-pattern-5e6g</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is the Singleton Pattern?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. The pattern is often used for managing resources like API clients, caching, or configuration that needs to be shared across various parts of the application.&lt;/p&gt;

&lt;p&gt;In the context of React, we usually want to implement a singleton for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Global state management (e.g., settings, themes).&lt;/li&gt;
&lt;li&gt;API client or data management (e.g., fetching data, caching).&lt;/li&gt;
&lt;li&gt;Logging or analytics service that needs to track events consistently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;How to Implement a Singleton Pattern in React&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Singleton for Managing Theme (Dark Mode Toggle)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's say you have a website that allows users to toggle between a light and dark theme. The Singleton design pattern can help manage the theme preference across the app to ensure that the same instance of the theme is applied everywhere.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;1. Create the Singleton Class for Theme Management&lt;/em&gt;&lt;br&gt;
This class will handle getting and setting the theme, and ensure there's only one instance used throughout the app.&lt;br&gt;
&lt;/p&gt;

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

class ThemeManager {
    constructor() {
        if(ThemeManager.instance) {
            this.theme = localStorage.getItem('theme') || 'light';
            ThemeManager.instance = this;
        }

        return ThemeManager.instance;
    }

    setTheme(newTheme) {
        this.theme = newTheme;
        localStorage.setItem('theme', newTheme);
    }

    getTheme() {
        return this.theme
    }
 }

 const themeManager = new ThemeManager(); // Create an instance
 export default themeManager; // Export the instance

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

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;2. Using the Singleton in Your React App&lt;/em&gt;&lt;br&gt;
Now, you can use this ThemeManager Singleton in your React components to apply and toggle the theme.&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from 'react';
import themeManager from './themeManager';
import './app.css';

const App = () =&amp;gt; {
  const [theme, setTheme ] = useState(themeManager.getTheme());

  useEffect(() =&amp;gt; {
    document.body.className = theme;
  }, [theme]);

  const toggleTheme = () =&amp;gt; {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    themeManager.setTheme(newTheme);
    setTheme(newTheme);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;SingleTone pattern with Theme Manager&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={toggleTheme}&amp;gt; Toggle to { theme === 'light' ? 'dark' : 'light' } Mode
      &amp;lt;/button&amp;gt;     
    &amp;lt;/div&amp;gt;
  )
}
export default App;

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

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;3. Apply the Styles for Themes&lt;/em&gt;&lt;br&gt;
Now you can define some CSS to switch between light and dark themes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* styles.css */
body.light {
  background-color: white;
  color: black;
}

body.dark {
  background-color: black;
  color: white;
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The Singleton (themeManager) ensures there’s only one instance of the theme across the entire application.&lt;/li&gt;
&lt;li&gt;When the user toggles the theme, it’s updated both in localStorage (so it persists on page reloads) and in the Singleton instance.&lt;/li&gt;
&lt;li&gt;The React component (in this case, App.js) listens for theme changes, and any other component can also access the same Singleton to get or update the theme.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Benefits of Using Singleton Here:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;_Global State Consistency: _The theme state is consistent throughout the app, and any component can access or modify it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Persistent Theme:&lt;/em&gt; By using localStorage, the theme persists across page reloads, and you ensure the same theme is used after the app is restarted.&lt;/p&gt;

&lt;p&gt;_Single Source of Truth: _The Singleton provides a single point of truth for the theme, ensuring that no other part of the app creates its own instance of the theme or overrides the global theme state.&lt;/p&gt;

&lt;p&gt;Check out my project on &lt;a href="https://github.com/padmajothiAthimoolam/Singleton-theme-manager" rel="noopener noreferrer"&gt;Singleton Theme manager &lt;/a&gt;&lt;/p&gt;

</description>
      <category>designpatterns</category>
      <category>react</category>
      <category>singleton</category>
      <category>globalstate</category>
    </item>
    <item>
      <title>Reusable Code in React</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Tue, 14 Jan 2025 18:51:39 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/reusable-code-in-react-f7</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/reusable-code-in-react-f7</guid>
      <description>&lt;p&gt;When working with React applications, especially in larger projects like an e-commerce app, you'll often encounter situations where components share similar functionality or structure but differ in logic or JSX. To improve code maintainability, avoid repetition, and ensure reusability, we can break down these scenarios and discuss possible solutions with code samples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;1. Problem: Two Components Have Different Logic, but Nearly Identical JSX&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario:&lt;/strong&gt;&lt;br&gt;
You have two components that look nearly identical (i.e., similar JSX structure), but their logic is different. For example, a component that displays a product list and a component that displays featured products. They share a similar layout but have different logic for fetching the products.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;br&gt;
In this case, you can extract the shared JSX into a reusable component and allow each parent component to pass its unique logic as props (such as the data to display or specific actions to trigger).&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ProductCard.js - Shared JSX component
import React from 'react';

const ProductCard = ({ product, onAddToCart }) =&amp;gt; {
  return (
    &amp;lt;div className="product-card"&amp;gt;
      &amp;lt;img src={product.image} alt={product.name} /&amp;gt;
      &amp;lt;h3&amp;gt;{product.name}&amp;lt;/h3&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;button onClick={() =&amp;gt; onAddToCart(product)}&amp;gt;Add to Cart&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default ProductCard;

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

&lt;/div&gt;



&lt;p&gt;Now, let's create two parent components: ProductList and FeaturedProducts, which have different logic but reuse ProductCard for their JSX.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ProductList.js - Fetching all products
import React, { useEffect, useState } from 'react';
import ProductCard from './ProductCard';

const ProductList = () =&amp;gt; {
  const [products, setProducts] = useState([]);

  useEffect(() =&amp;gt; {
    // Fetch all products (this is just an example)
    fetch('/api/products')
      .then((res) =&amp;gt; res.json())
      .then((data) =&amp;gt; setProducts(data));
  }, []);

  const handleAddToCart = (product) =&amp;gt; {
    // Add to cart logic
    console.log('Added to cart:', product.name);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;All Products&amp;lt;/h2&amp;gt;
      {products.map((product) =&amp;gt; (
        &amp;lt;ProductCard key={product.id} product={product} onAddToCart={handleAddToCart} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
};

export default ProductList;

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

&lt;/div&gt;



&lt;p&gt;FeaturedProducts.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// FeaturedProducts.js - Fetching only featured products
import React, { useEffect, useState } from 'react';
import ProductCard from './ProductCard';

const FeaturedProducts = () =&amp;gt; {
  const [featuredProducts, setFeaturedProducts] = useState([]);

  useEffect(() =&amp;gt; {
    // Fetch featured products (this is just an example)
    fetch('/api/featured-products')
      .then((res) =&amp;gt; res.json())
      .then((data) =&amp;gt; setFeaturedProducts(data));
  }, []);

  const handleAddToCart = (product) =&amp;gt; {
    // Add to cart logic
    console.log('Featured Product added to cart:', product.name);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Featured Products&amp;lt;/h2&amp;gt;
      {featuredProducts.map((product) =&amp;gt; (
        &amp;lt;ProductCard key={product.id} product={product} onAddToCart={handleAddToCart} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
};

export default FeaturedProducts;

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

&lt;/div&gt;



&lt;p&gt;Both components (ProductList and FeaturedProducts) share similar JSX but have different logic for fetching products. By using a reusable ProductCard component, you avoid code duplication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;2. Two Components Have the Same Logic, but Different JSX&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario:&lt;/strong&gt;&lt;br&gt;
You have two components that share the same logic (e.g., fetching products), but they display the data in different layouts. For example, a grid view for products and a list view for products.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;br&gt;
In this case, you can extract the common logic into a custom hook or a shared context and pass the layout-specific JSX (or rendering logic) as props to a reusable presentational component.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&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;// useProducts.js - Shared hook for fetching products
import { useState, useEffect } from 'react';

const useProducts = () =&amp;gt; {
  const [products, setProducts] = useState([]);

  useEffect(() =&amp;gt; {
    // Fetch products
    fetch('/api/products')
      .then((res) =&amp;gt; res.json())
      .then((data) =&amp;gt; setProducts(data));
  }, []);

  return products;
};

export default useProducts;

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

&lt;/div&gt;



&lt;p&gt;Now, we can create two components that share the logic but have different rendering (layout) styles.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// GridView.js - Grid layout for products
import React from 'react';
import useProducts from './useProducts';
import ProductCard from './ProductCard';

const GridView = () =&amp;gt; {
  const products = useProducts();

  return (
    &amp;lt;div className="product-grid"&amp;gt;
      {products.map((product) =&amp;gt; (
        &amp;lt;ProductCard key={product.id} product={product} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
};

export default GridView;

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

&lt;/div&gt;



&lt;p&gt;ListView.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ListView.js - List layout for products
import React from 'react';
import useProducts from './useProducts';
import ProductCard from './ProductCard';

const ListView = () =&amp;gt; {
  const products = useProducts();

  return (
    &amp;lt;div className="product-list"&amp;gt;
      {products.map((product) =&amp;gt; (
        &amp;lt;ProductCard key={product.id} product={product} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
};

export default ListView;

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

&lt;/div&gt;



&lt;p&gt;Both GridView and ListView share the same logic for fetching products (via the useProducts hook) but have different layouts. By separating the logic (with a custom hook) and reusing the ProductCard component, you maintain clean code while supporting different visual layouts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;3. Problem: Two Components Have Similar Logic and JSX&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario:&lt;/strong&gt;&lt;br&gt;
You have two components with both similar logic and nearly identical JSX. For example, you have a product details page and a checkout page that both require displaying a list of items in a cart, and the logic for adding/removing items is almost identical.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;br&gt;
In this case, you can abstract the shared code into a reusable component and wrap it in a higher-order component (HOC) or a shared state management solution (like Context API) to further eliminate redundancy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&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;// CartItem.js - Shared component for displaying a cart item
import React from 'react';

const CartItem = ({ product, onRemove }) =&amp;gt; (
  &amp;lt;div className="cart-item"&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;button onClick={() =&amp;gt; onRemove(product.id)}&amp;gt;Remove&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
);

export default CartItem;

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

&lt;/div&gt;



&lt;p&gt;Now, we can create two components: CartPage and CheckoutPage, which use the shared CartItem component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// CartPage.js - Cart page showing cart items
import React, { useState } from 'react';
import CartItem from './CartItem';

const CartPage = () =&amp;gt; {
  const [cartItems, setCartItems] = useState([
    { id: 1, name: 'Laptop', price: 999 },
    { id: 2, name: 'Smartphone', price: 599 },
  ]);

  const handleRemoveItem = (id) =&amp;gt; {
    setCartItems(cartItems.filter((item) =&amp;gt; item.id !== id));
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Your Cart&amp;lt;/h2&amp;gt;
      {cartItems.map((item) =&amp;gt; (
        &amp;lt;CartItem key={item.id} product={item} onRemove={handleRemoveItem} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
};

export default CartPage;

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

&lt;/div&gt;



&lt;p&gt;checkoutPage.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// CheckoutPage.js - Checkout page showing cart items (same logic)
import React, { useState } from 'react';
import CartItem from './CartItem';

const CheckoutPage = () =&amp;gt; {
  const [cartItems, setCartItems] = useState([
    { id: 1, name: 'Laptop', price: 999 },
    { id: 2, name: 'Smartphone', price: 599 },
  ]);

  const handleRemoveItem = (id) =&amp;gt; {
    setCartItems(cartItems.filter((item) =&amp;gt; item.id !== id));
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Checkout&amp;lt;/h2&amp;gt;
      {cartItems.map((item) =&amp;gt; (
        &amp;lt;CartItem key={item.id} product={item} onRemove={handleRemoveItem} /&amp;gt;
      ))}

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

export default CheckoutPage;

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

&lt;/div&gt;



&lt;p&gt;Both CartPage and CheckoutPage share the same logic for displaying and removing items from the cart. By using a shared CartItem component, you can eliminate redundancy and keep the code clean, even when the JSX structure and logic are similar.&lt;/p&gt;

&lt;p&gt;By following these strategies—whether it’s breaking down logic into custom hooks, creating shared components, or utilizing context—React developers can significantly reduce redundancy and build applications that are both easier to maintain and extend.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Comparing Jest, React Testing Library, and Playwright: Testing Approaches for React Applications</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Mon, 28 Oct 2024 15:07:34 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/comparing-jest-react-testing-library-and-playwright-testing-approaches-for-react-applications-15ic</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/comparing-jest-react-testing-library-and-playwright-testing-approaches-for-react-applications-15ic</guid>
      <description>&lt;p&gt;&lt;strong&gt;1. Jest&lt;/strong&gt;&lt;br&gt;
Purpose: Jest is a testing framework for JavaScript, commonly used for unit and integration testing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Usage in React:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It provides a simple way to run tests, mock functions, and perform assertions.&lt;br&gt;
Typically used for testing individual components and utility functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&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 { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders a message', () =&amp;gt; {
  render(&amp;lt;MyComponent /&amp;gt;);
  const linkElement = screen.getByText(/hello world/i);
  expect(linkElement).toBeInTheDocument();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. React Testing Library (RTL)&lt;/strong&gt;&lt;br&gt;
Purpose: RTL is a testing utility specifically designed for testing React components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Usage in React:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Focuses on testing components in a way that resembles how users interact with them.&lt;br&gt;
Encourages best practices, like querying by text rather than implementation details.&lt;br&gt;
Works seamlessly with Jest.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&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 { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('displays a message to the user', () =&amp;gt; {
  render(&amp;lt;MyComponent /&amp;gt;);
  expect(screen.getByRole('heading')).toHaveTextContent('Hello World');
});

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Playwright&lt;/strong&gt;&lt;br&gt;
Purpose: Playwright is an end-to-end testing framework used for testing web applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Usage in React:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Tests the entire application flow in a browser, simulating user interactions.&lt;/p&gt;

&lt;p&gt;Useful for testing scenarios where multiple components and pages interact, such as form submissions, navigation, and API calls.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&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 { test, expect } = require('@playwright/test');

test('homepage has a welcome message', async ({ page }) =&amp;gt; {
  await page.goto('http://localhost:3000');
  const welcomeMessage = await page.textContent('h1');
  expect(welcomeMessage).toBe('Welcome to My App');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Summary of Differences&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Scope:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Jest:&lt;/em&gt; Unit and integration testing (individual components and functions).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;React Testing Library:&lt;/em&gt; Component testing focusing on user interactions.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Playwright:&lt;/em&gt; End-to-end testing simulating user behavior in a real browser.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Approach:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Jest:&lt;/em&gt; Uses assertions to validate outcomes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;React Testing Library:&lt;/em&gt; Encourages testing as users would interact with the app.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Playwright:&lt;/em&gt; Interacts with the application like a real user, covering all components and their integrations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Execution:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Jest:&lt;/em&gt; Runs tests in a Node.js environment.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;React Testing Library:&lt;/em&gt; Runs with Jest or another framework but tests components rendered in a simulated DOM.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Playwright:&lt;/em&gt; Runs tests in real browsers, checking for functionality across multiple environments.&lt;/p&gt;

</description>
      <category>react</category>
      <category>jest</category>
      <category>playwright</category>
      <category>testing</category>
    </item>
    <item>
      <title>Handling Environment Variables in Vite</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Mon, 21 Oct 2024 21:58:17 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/handling-environment-variables-in-vite-480b</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/handling-environment-variables-in-vite-480b</guid>
      <description>&lt;p&gt;In modern web development, managing sensitive data such as API keys, database credentials, and various configurations for different environments is essential. Storing these variables directly in code can pose security risks and complicate deployment. Vite, a modern front-end build tool, provides a straightforward way to manage environment variables through .env files.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a .env File?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A .env file is a simple configuration file used to define environment-specific variables. These variables can be accessed within your application while remaining separate from the source code. This practice allows for easy management of different environments—development, staging, and production—without hardcoding sensitive data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Environment Variables in Vite&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Vite comes with built-in support for environment variables, making it easier to inject different values based on the current environment. Here’s how Vite handles environment variables:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Global Variables:&lt;/strong&gt; Vite injects environment variables at build time.&lt;br&gt;
&lt;strong&gt;Prefixed Variables:&lt;/strong&gt; Only variables prefixed with VITE_ are exposed to the client-side JavaScript code for security reasons. Any variables not prefixed this way won’t be accessible in the browser.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example of a Vite environment variable:&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;VITE_API_URL=https://api.example.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Setting Up .env Files in Vite&lt;br&gt;
Vite supports multiple .env files, allowing you to define environment variables for specific environments. Here’s a typical setup:&lt;/p&gt;

&lt;p&gt;.env: Default file for environment variables shared across all environments.&lt;br&gt;
.env.development: Variables specific to the development environment.&lt;br&gt;
.env.production: Variables specific to the production environment.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Example .env File:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VITE_API_URL=https://api.example.com
VITE_APP_NAME=MyViteApp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Example .env.development File:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VITE_API_URL=http://localhost:3000
VITE_DEBUG_MODE=true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Example .env.production File:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VITE_API_URL=https://api.production.com
VITE_DEBUG_MODE=false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Accessing Environment Variables in Vite&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To access environment variables inside your Vite project, use the import.meta.env object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(import.meta.env.VITE_API_URL); // Outputs the value of VITE_API_URL

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

&lt;/div&gt;



&lt;p&gt;Vite automatically replaces import.meta.env values during the build process based on the current environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Managing Multiple Environments&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Vite’s .env files can be customized for different environments like development, staging, and production. Depending on which environment you're in, Vite will load the appropriate .env file:&lt;/p&gt;

&lt;p&gt;Running vite loads the .env.development file.&lt;br&gt;
Running vite build loads the .env.production file.&lt;br&gt;
Running in a specific environment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vite --mode staging

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Debugging Environment Variables&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;If you’re having issues with environment variables not working as expected, check the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Variable Prefix: Ensure all client-side variables have the &lt;strong&gt;VITE_&lt;/strong&gt; prefix, as Vite ignores variables without this prefix.&lt;/li&gt;
&lt;li&gt;Env Loading Order: Make sure .env and environment-specific files are in the project root and named correctly.&lt;/li&gt;
&lt;li&gt;Check Build Process: Use console.log(import.meta.env) to see all available environment variables during development.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Vite’s built-in support for environment variables through .env files makes it easy to manage configurations across different environments. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>vite</category>
      <category>environment</category>
    </item>
    <item>
      <title>Transpiler vs Polyfills</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Mon, 07 Oct 2024 23:59:13 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/transpiler-vs-ployfills-1i5l</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/transpiler-vs-ployfills-1i5l</guid>
      <description>&lt;p&gt;In modern web development, maintaining compatiablity across different browsers and environments is a crucial challenge. Two important tools that help developers overcome this issue are transpilers and polyfills. Both serve the purpose of making code work across different platforms, they operate in distinct ways.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Transpilers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A transpiler is a tool that converts code written in one language ot syntax to another language or syntax. Specially, in the context of Javascript, transpilers convert modern Javascript (ES6+) into older versions of Javascript (like ES5) that can be understood by older browsers on environments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;key points:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;- Syntax-Level Conversion:&lt;/em&gt; A transpiler converts code by transforming newer syntax and features( e.g. let,const, arrow functions) into equivalent constructs in older version. It ensures the same code runs across different environments.&lt;/p&gt;

&lt;p&gt;E.g. &lt;em&gt;&lt;strong&gt;Babel&lt;/strong&gt;&lt;/em&gt; - Converts modern ES6+ code into ES5.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;TypeScript Compiler&lt;/em&gt;&lt;/strong&gt; - Converts Typescript into plain JavaScript.&lt;/p&gt;

&lt;p&gt;ES6 code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let greet = () =&amp;gt; console.log("Hello World!");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A transpiler would convert it to ES5, looks like :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var greet = function () {
console.log("Hello World!");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;What is Polyfills?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A Polyfill is a piece of code, that provides missing functionality in older browsers or environments.It "fills in" the gaps where. a certain feature is not natively supported.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;key points:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;-Feature Level Emulation:&lt;/em&gt; Unlike a transpiler, which transforms code syntax, a polyfill implements missing features. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Polyfills are added at runtime and do not modify the source code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;E.g - includes polyfills&lt;/p&gt;

&lt;p&gt;For browsers that don't support the Array.prototype.includes method, a polyfill can be implemented 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;if(!Array.prototype.includes) {
Array.prototype.includes = 
  function(searchElement) {
    return this.indexOf(searchElement) !== -1
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key Difference&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fz6w6jdqlx9u64g9yrhsu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fz6w6jdqlx9u64g9yrhsu.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By using transpiler, we can ensure the code is compatible with older environments, while polyfills allow to add missing functionality. Together they allow developers to write modern, efficient code without worrying about breaking support for older platforms.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>polyfills</category>
      <category>transpiller</category>
      <category>es6</category>
    </item>
    <item>
      <title>The Power of Redux Toolkit's createSlice</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Thu, 26 Sep 2024 15:37:27 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/the-power-of-redux-toolkits-createslice-1p1k</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/the-power-of-redux-toolkits-createslice-1p1k</guid>
      <description>&lt;p&gt;createSlice is one of the most powerful and essential features of Redux Toolkit (RTK). It simplifies the process of writing Redux logic by reducing boilerplate and offering a cleaner, more maintainable code structure. This article will explore what createSlice is, how it works, and why it's a game-changer for Redux development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is createSlice?&lt;/strong&gt;&lt;br&gt;
createSlice is a utility in Redux Toolkit that allows developers to define a slice of the Redux state in a highly efficient way. It combines the logic for actions and reducers into a single, concise format, automating many tedious tasks such as action creation and action type definition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Features of createSlice&lt;/strong&gt;&lt;br&gt;
Simplified Reducer Logic: With createSlice, you no longer need to write action types and action creators manually.&lt;br&gt;
Automatic Action Creation: It generates action creators automatically based on the defined reducer methods.&lt;br&gt;
Built-in Immutability with Immer: Redux Toolkit uses Immer internally, which allows writing "mutating" code that adheres to Redux’s immutability principles.&lt;br&gt;
Combines Reducers and Actions: Reduces the need for separate files for actions and reducers, allowing you to keep related logic together.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Use createSlice&lt;/strong&gt;&lt;br&gt;
The core idea of createSlice is that it allows you to create a "slice" of your application's state, and you can define all related logic (state, reducers, actions) within it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Defining a Slice&lt;/strong&gt;&lt;br&gt;
A slice includes three main things:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Name:&lt;/em&gt; The name of the slice, used as the action type prefix.&lt;br&gt;
&lt;em&gt;Initial state:&lt;/em&gt; The starting state of the slice.&lt;br&gt;
&lt;em&gt;Reducers:&lt;/em&gt; Functions that handle how the state is updated in response to actions.&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 counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) =&amp;gt; {
      state.value += 1; // Immer allows "mutating" the state directly
    },
    decrement: (state) =&amp;gt; {
      state.value -= 1;
    },
    incrementByAmount: (state, action) =&amp;gt; {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Reducer Logic Simplified&lt;/strong&gt;&lt;br&gt;
In traditional Redux, reducers require creating a new copy of the state every time it is updated, making the code more verbose. With createSlice can directly "mutate" the state. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Automatic Action Creators&lt;/strong&gt;&lt;br&gt;
When you define reducers in createSlice, Redux Toolkit automatically generates corresponding action creators. For example, based on the code above:&lt;/p&gt;

&lt;p&gt;The increment reducer generates the increment() action.&lt;br&gt;
The decrement reducer generates the decrement() action.&lt;br&gt;
The incrementByAmount reducer generates the incrementByAmount(payload) action, where payload is passed as an argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dispatch(increment());         // Dispatches increment action
dispatch(decrement());         // Dispatches decrement action
dispatch(incrementByAmount(5)); // Dispatches action with payload of 5

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Benefits of Using createSlice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Reduced Boilerplate:&lt;/em&gt; One of the main pain points with traditional Redux was the amount of boilerplate code needed for action types, action creators, and reducers. createSlice drastically reduces this by co-locating these in one function.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Immutability without Complexity:&lt;/em&gt; Immer is baked into Redux Toolkit, so you can "mutate" state directly in your reducers, but the actual updates are done immutably under the hood. This leads to simpler and cleaner code without the risk of accidentally mutating state.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Automatic Action Types:&lt;/em&gt; Each reducer you define in createSlice automatically generates an action type that includes the slice name, ensuring no naming collisions and making it easier to manage larger applications.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Easier Debugging:&lt;/em&gt; Redux DevTools and time-travel debugging work seamlessly with createSlice, so you can inspect every action and state change efficiently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;createSlice in Redux Toolkit is a game-changer for state management in React. By combining reducers, actions, and initial state into one streamlined function, it simplifies the Redux development process, allowing you to focus on building your application without worrying about boilerplate code. Its integration with Immer ensures that state updates remain immutable while providing a natural, intuitive API for handling complex state logic. Whether you're managing simple counters or complex arrays of objects, createSlice makes state management in Redux more efficient and maintainable.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Simplifying Fetching Data with React Query: Replacing useEffect</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Fri, 20 Sep 2024 15:15:54 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/simplifying-fetching-data-with-react-query-replacing-useeffect-ac4</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/simplifying-fetching-data-with-react-query-replacing-useeffect-ac4</guid>
      <description>&lt;p&gt;&lt;strong&gt;React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React Query's core functionality revolves around fetching and caching data from an API and handling state management, while search engines like Google allow us to query and retrieve relevant information from an extensive database. In this blog, we'll explore how React Query can replace useEffect for data fetching, leading to cleaner and more maintainable code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React Query is a data-fetching library that simplifies the process of managing server state in React applications. It provides hooks for fetching, caching, and syncing server data without the complexity that often comes with useEffect.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Replace useEffect?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While useEffect is useful for managing side effects like data fetching, it can lead to complicated code structures. You often find yourself writing multiple effects for different data dependencies, handling loading states, and managing cleanup functions. This can quickly become messy&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benefits of Using React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Simplified Data Fetching:&lt;/strong&gt;&lt;/em&gt;  React Query abstracts away the complexities of data fetching and state management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Automatic Caching:&lt;/em&gt;&lt;/strong&gt; It automatically caches fetched data, reducing unnecessary requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Background Updates:&lt;/em&gt;&lt;/strong&gt; Data can be kept fresh in the background, ensuring users see the most up-to-date information.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Built-in Loading and Error States:&lt;/em&gt;&lt;/strong&gt; React Query provides loading and error states out of the box, making UI management easier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Replacing useEffect with React Query&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s consider an example where we fetch user data from an API. Here’s how you might traditionally use useEffect:&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, { useEffect, useState } from 'react';

const UserProfile = () =&amp;gt; {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() =&amp;gt; {
    const fetchData = async () =&amp;gt; {
      try {
        const response = await fetch('https://api.example.com/user');
        if (!response.ok) throw new Error('Network response was not ok');
        const data = await response.json();
        setUser(data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  if (error) return &amp;lt;div&amp;gt;Error: {error.message}&amp;lt;/div&amp;gt;;

  return &amp;lt;div&amp;gt;{user.name}&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let’s see how we can refactor this code using React Query:&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 { useQuery } from 'react-query';

const fetchUser = async () =&amp;gt; {
  const response = await fetch('https://api.example.com/user');
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
};

const UserProfile = () =&amp;gt; {
  const { data: user, isLoading, isError, error } = useQuery('user', fetchUser);

  if (isLoading) return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  if (isError) return &amp;lt;div&amp;gt;Error: {error.message}&amp;lt;/div&amp;gt;;

  return &amp;lt;div&amp;gt;{user.name}&amp;lt;/div&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;useQuery Hook:&lt;/em&gt;&lt;/strong&gt; This hook replaces useEffect for data fetching. It accepts a unique key (in this case, 'user') and a function to fetch the data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Loading and Error Handling:&lt;/em&gt;&lt;/strong&gt;  Instead of managing loading and error states manually, React Query provides isLoading, isError, and error directly from the useQuery response.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;_Cleaner Code: _&lt;/strong&gt;The resulting code is simpler and easier to read. You don’t have to worry about cleanup or dependency arrays.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React Query significantly streamlines the process of managing server state in React applications. By replacing useEffect with React Query’s powerful hooks, you can simplify your code, improve readability, and enhance user experience. If you haven’t yet tried React Query, now is a great time to start exploring its capabilities!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>React Code Review Essentials: A Detailed Checklist for Developers</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Mon, 09 Sep 2024 16:08:35 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/react-code-review-essentials-a-detailed-checklist-for-developers-20n2</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/react-code-review-essentials-a-detailed-checklist-for-developers-20n2</guid>
      <description>&lt;p&gt;&lt;strong&gt;1. Overview&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;-&lt;strong&gt;README:&lt;/strong&gt; Ensure the project has a Readme file with instructions on how to run locally and other useful information.&lt;/p&gt;

&lt;p&gt;-&lt;strong&gt;Error-Free code:&lt;/strong&gt; Verify that the code runs without errors.&lt;br&gt;
-&lt;strong&gt;Functionality:&lt;/strong&gt; Confirm that the application looks good on mobile devices.&lt;br&gt;
-&lt;strong&gt;Responsiveness:&lt;/strong&gt; Check if the application looks good on mobile devices&lt;br&gt;
-&lt;strong&gt;Linting:&lt;/strong&gt; Verify if the codebase uses eslint.&lt;br&gt;
-&lt;strong&gt;.gitignore:&lt;/strong&gt; Ensure no dist files, editor/IDE files are checked in.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Tip:&lt;/strong&gt;&lt;/em&gt;  &lt;a href="https://www.toptal.com/developers/gitignore" rel="noopener noreferrer"&gt;The Toptal Gitignore generator&lt;/a&gt; helps you create customized .gitignore files to exclude unnecessary or sensitive files from being tracked by Git based on your project's technology stack. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Testing&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Unit tests:&lt;/strong&gt; Confirm there are unit tests for crucial parts of the codebase.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Naming:&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Consistency&lt;/strong&gt;: Ensure filenames, variables, functions, and modules have consistent casing and descriptive names.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Code quality:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Code duplication&lt;/strong&gt;: Look for blocks of code that can refactored to reduce duplication.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Simplify code&lt;/strong&gt;: Simplify overly complex code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Unused code&lt;/strong&gt;: Remove unused or unreachable code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Commented-out code&lt;/strong&gt;: Delete commented-out code&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Console Logs&lt;/strong&gt;: Remove console.log statements unless necessary.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Comments&lt;/strong&gt;: Remove unnecessary comments that describe "how" and add comments where needed that describe "why".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;5. ES6+ features&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Spread operator&lt;/strong&gt;: Utilize the spread operator where applicable.
-** Destructuring**: use destructuring for arrays and objects.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Var or Let/Const&lt;/strong&gt;: Replace var with let or const&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Arrow functions&lt;/strong&gt;: Use arrow functions consistently.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lodash/ES6&lt;/strong&gt;: Ensure consistency in using lodash, ES6 or older Javascript for data transformation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;6. React Best practices:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Minimize Render logic&lt;/strong&gt;: Move logic out of render method into helper methods, container components, or Redux actions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Side effects&lt;/strong&gt;: Move code with side effects( eg. ajax calls) out of render methods.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Components size&lt;/strong&gt;: split up larger components to reduce duplication and adhere to the single responsibility principle.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Destructuring Props&lt;/strong&gt;: Destructure props in Es6 components.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Functional component&lt;/strong&gt;s: Use functional components for stateless components&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Immutable Props&lt;/strong&gt;: Ensure props are not modified within components.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;7. Redux:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;State Mutations&lt;/strong&gt;: Verify the reducers do not mutate the state.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;8. Component Design:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Component size&lt;/strong&gt;: Keep components small and break them down into child components if necessary.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JSX size&lt;/strong&gt;: Ensure JSX markup is no more than 50 lines,&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Function comments&lt;/strong&gt; - Add comments describing what each function does.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Linter errors&lt;/strong&gt;: Ensure code id free of linter errors.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;React warnings&lt;/strong&gt;: Resolve any react warnings, such and missing key props in array.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DRY principle&lt;/strong&gt;: Avoid repeating code, ensure code is reusable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Code Pattens&lt;/strong&gt;: Adhere to existing code patterns and naming conventions&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Usused props&lt;/strong&gt;: Remove any unused props&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Styling&lt;/strong&gt;: Prefer using common styling files over inline styles.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Constants and Enums&lt;/strong&gt;: Avoid hardcoded values. Use constants and group similar values under Enum.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Interfaces and Types&lt;/strong&gt;: Ensure proper use of interfaces and types, Extending them where required.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;9. API and Async Handling"&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Service Layer&lt;/strong&gt;: create a service layer for API calls.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;promises/Async/Await&lt;/strong&gt;: Use Promises or async/await for asynchronous operations and handle API rejections.&lt;/li&gt;
&lt;li&gt;Avoid infinite call inside loops.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Exception Handling&lt;/strong&gt;: Implement proper exception handling and resource cleanup.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Timers&lt;/strong&gt;: Unregister timers in clean-up effects if registered during mounting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;10. Additional considerations:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Image Alt Text&lt;/strong&gt;: Ensure all images have appropriate alt attributes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Git commit message&lt;/strong&gt;s: Use small and understandable commit messages.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;NPM package&lt;/strong&gt;: Check for new npm packages and avoid functionality duplicates.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Imports&lt;/strong&gt;: Ensure imports to avoid bundling unused library parts.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Translations&lt;/strong&gt;: Verify that new text areas are translated if translations are used.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Typescript&lt;/strong&gt;: Fix any missing or invalid types, avoid any types unless necessary.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Boolean naming&lt;/strong&gt;: Use prefixes like is/are/should for boolean variables.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Function names&lt;/strong&gt;: Ensure functions declare their purpose clearly and name them according to their action.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hardcoded values&lt;/strong&gt;: Avoid hardcoded names, paths and values.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Backward compatibility&lt;/strong&gt;: Ensure backward compatibility in props and method parameters.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Form Validation&lt;/strong&gt;: Check for form validation and proper handling of errors.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Async Methods&lt;/strong&gt;: Optimize async methods for parallel execution where possible.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use this checklist as a guide to review and improve React code ensuring high-quality, maintainable, and performant applications.&lt;/p&gt;

</description>
      <category>react</category>
      <category>codereview</category>
      <category>bestpractices</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Understanding error={!!error} in React: What Does it Mean?</title>
      <dc:creator>padmajothi Athimoolam</dc:creator>
      <pubDate>Tue, 27 Aug 2024 21:29:42 +0000</pubDate>
      <link>https://dev.to/padmajothi_athimoolam_23d/understanding-errorerror-in-react-what-does-it-mean-3i6e</link>
      <guid>https://dev.to/padmajothi_athimoolam_23d/understanding-errorerror-in-react-what-does-it-mean-3i6e</guid>
      <description>&lt;p&gt;In React applications, handling and displaying errors gracefully is crucial for creating a user-friendly experience. One common pattern is the usage of error={!!error}. This pattern leverages Javascript's type coercion to ensure a boolean value is used for conditional rendering or logic. But what does it really mean, and why is it used? &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Double Exclamation Mark(!!) Operator&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The !! operator is used to convert a value to a boolean. It's a shorthand for ensuring that a value is either true or false, depending on truthiness. Here's a breakdown of how it works.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;1. Single Exclamation Mark (!): *&lt;/em&gt; &lt;br&gt;
When used once,! it converts a value to its boolean negation. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;!true   //false
!false  //true
!0      //true ( 0 is falsy)
!1      //false ( 1 is truthy)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Double Exclamation Mark(!!)&lt;/strong&gt;&lt;br&gt;
Applying ! twice converts any value to boolean:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;!!true    //true
!!false  //false
!!0      //false
!!1      //true
!!'hello' //true ( non-empty strings are truthy)
!!''     //false ( empty strings are falsy)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Essentially !! forces any value to be explicitly true or false.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;why use !! in React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In React, you might encounter !! when dealing with conditional rendering or props where a boolean value is required.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Ensures Boolean Values:&lt;/strong&gt; React components often expect boolean values for certain props such as error, disabled or visible. Using !! guarantees that these props receive a boolean value, preventing unexpected behavior.
&lt;strong&gt;- Consistency in Conditional Rendering:&lt;/strong&gt; When using conditional rendering, it's crucial to ensure the condition evaluates to a boolean. This avoids errors and ensures consistent rendering logic.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Practical Examples in React&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: Conditional Rendering&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;consider a scenario where you want to display an error message only if an &lt;em&gt;error&lt;/em&gt; exists:&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';

const ErrorMessage = ({ error }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    {error &amp;amp;&amp;amp; &amp;lt;p style={{ color: 'red' }}&amp;gt;{error}&amp;lt;/p&amp;gt;}
  &amp;lt;/div&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;em&gt;error&lt;/em&gt; can be a string or null/ undefined. If &lt;em&gt;error&lt;/em&gt; is a non empty string , the message will be displayed. If &lt;em&gt;error&lt;/em&gt; is falsy (null or undefined), the message won't be rendered.&lt;/p&gt;

&lt;p&gt;However, if error is always a boolean or if you want to ensure that error is explicitly a boolean you can use !!.&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';

const ErrorMessage = ({ error }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    {!!error &amp;amp;&amp;amp; &amp;lt;p style={{ color: 'red' }}&amp;gt;An error occurred&amp;lt;/p&amp;gt;}
  &amp;lt;/div&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, !!error ensures that the expression evaluates to true or false, making the rendering logic more predictable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2: Handling Props&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When passing prop that expects a boolean, !! ensures the correct type:&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';

const SubmitButton = ({ isDisabled }) =&amp;gt; (
  &amp;lt;button disabled={!!isDisabled}&amp;gt;Submit&amp;lt;/button&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, !!&lt;em&gt;isDisabled&lt;/em&gt; guarantees that the disabled attribute will receive a boolean value, even if &lt;em&gt;isDisabled&lt;/em&gt; is undefined, null or any other falsy value.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Common use cases *&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Form Validation:&lt;/strong&gt; When handling form validation, using !! can ensure that validation states (like &lt;em&gt;hasErrors&lt;/em&gt;) are properly converted to booleans for rendering or logic checks&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic classes:&lt;/strong&gt; In class names or style conditions, !! can be used to ensure boolean values for applying conditional styles or classes.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const buttonClass = `btn ${!!isPrimary ? 'btn-primary' : 'btn-secondary'}`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The !! operator is used for ensuring values are explicitly converted to booleans in Javascript and React applications. It can prevent potential bugs and ensure your components behave as expected. This is particularly useful for conditional rendering and managing props where boolean values are required.&lt;/p&gt;

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