<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maciej Poppek on Medium]]></title>
        <description><![CDATA[Stories by Maciej Poppek on Medium]]></description>
        <link>https://medium.com/@maciejpoppek?source=rss-ac4582d6194a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FuY3Vicxz5-5K1iTW0iQHQ.jpeg</url>
            <title>Stories by Maciej Poppek on Medium</title>
            <link>https://medium.com/@maciejpoppek?source=rss-ac4582d6194a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:13:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maciejpoppek/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unlocking the Power of the Facade Pattern in React for Clean Code]]></title>
            <link>https://blog.devgenius.io/facade-pattern-in-react-hooks-165e0b505ed6?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/165e0b505ed6</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 14:44:01 GMT</pubDate>
            <atom:updated>2024-10-02T16:23:03.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDAo9MkuWD-FILr1BPsk8A.jpeg" /><figcaption><a href="https://www.freepik.com/free-photo/construction-silhouette_4291509.htm#query=construction&amp;position=2&amp;from_view=keyword&amp;track=ais_hybrid&amp;uuid=d4bba53a-99ba-42f1-a54f-c33c42abc94b">Image by jcomp on Freepik</a></figcaption></figure><p>The <strong>Facade pattern</strong> is a structural design pattern that provides a simplified interface to a complex subsystem. In the context of React development, <strong>this pattern can be used to combine multiple hooks or state management logic into a single, easy-to-use interface</strong>. By using the <strong>Facade pattern</strong>, we can hide the complexity of multiple custom hooks or state management tools like <strong>Jotai</strong> and expose a unified API for components to consume.</p><p>In this article, we’ll explore how to use the Facade pattern with <strong>React Hooks</strong> and <strong>Jotai</strong> for managing product listing, filtering, and sorting in an <strong>e-commerce</strong> setting.</p><ul><li><a href="https://blog.devgenius.io/another-react-design-pattern-you-use-but-you-are-not-even-aware-of-it-82b01e5201be">Cool React Design Pattern You Use, But You Are Not Even Aware of It</a></li><li><a href="https://blog.devgenius.io/the-react-design-pattern-youre-using-without-even-realizing-it-e85385fd354d">The React Design Pattern You’re Using Without Even Realizing It</a></li></ul><p><strong>What is the Facade Pattern?</strong></p><p>The Facade pattern provides a simplified interface to a complex system by hiding intricate details behind an easy-to-use API. In React applications, you can apply this pattern by combining complex logic or multiple hooks into a single custom hook.</p><p><strong>Implementing Facade Pattern for Product Filtering</strong></p><p>We will implement a product listing component that fetches products from an API, allows filtering by category and price, and supports sorting by price or relevance.</p><p><strong>Step 1: Setting up Jotai for Global Filter and Sort State</strong></p><p>First, we’ll create atoms for managing <strong>filter</strong>, <strong>sort</strong>, and <strong>product data</strong> states globally.</p><pre>// filterAtom.model.ts<br>import { atom } from &#39;jotai&#39;;<br><br>export const filterAtom = atom({<br>  category: &#39;&#39;,<br>  priceRange: [0, 1000],<br>});</pre><pre>// sortAtom.model.ts<br>import { atom } from &#39;jotai&#39;;<br><br>export const sortAtom = atom(&#39;relevance&#39;);</pre><pre>// productsAtom.model.ts<br>import { atom } from &#39;jotai&#39;;<br><br>export const productsAtom = atom([]);</pre><p>Here, we define:</p><ul><li>filterAtom: Manages the selected category and price range.</li><li>sortAtom: Manages sorting by relevance or price.</li><li>productsAtom: Holds the list of fetched products.</li></ul><p><strong>Step 2: Create the useFetchProducts Hook</strong></p><p>We’ll now create a custom hook to fetch products based on the current filter and sort state. The API will adjust the response based on these parameters.</p><pre>// useFetchProducts.util.ts<br>import { useEffect } from &#39;react&#39;;<br>import { useAtom } from &#39;jotai&#39;;<br>import { filterAtom } from &#39;./model/filterAtom.model&#39;;<br>import { sortAtom } from &#39;./model/sortAtom.model&#39;;<br>import { productsAtom } from &#39;./model/productsAtom.model&#39;;<br><br>export function useFetchProducts(apiUrl: string) {<br>  const [filter] = useAtom(filterAtom);<br>  const [sort] = useAtom(sortAtom);<br>  const [, setProducts] = useAtom(productsAtom);<br><br>  const fetchData = async () =&gt; {<br>    try {<br>      const response = await fetch(<br>        `${apiUrl}?category=${filter.category}&amp;minPrice=${filter.priceRange[0]}&amp;maxPrice=${filter.priceRange[1]}&amp;sort=${sort}`<br>      );<br>      const data = await response.json();<br>      setProducts(data);<br>    } catch (error) {<br>      console.error(&#39;Error fetching products:&#39;, error);<br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    fetchData();<br>  }, [apiUrl, filter, sort, setProducts]);<br>}</pre><p>This hook automatically fetches products whenever the filter or sort state changes and stores the result in the productsAtom.</p><p><strong>Step 3: Implement the Facade Hook for Product Listing</strong></p><p>Next, let’s create the Facade hook that will simplify access to the filtering, sorting, and product fetching logic.</p><pre>// useProductFacade.util.ts<br>import { useAtom } from &#39;jotai&#39;;<br>import { filterAtom } from &#39;./model/filterAtom.model&#39;;<br>import { sortAtom } from &#39;./model/sortAtom.model&#39;;<br>import { productsAtom } from &#39;./model/productsAtom.model&#39;;<br>import { useFetchProducts } from &#39;./util/useFetchProducts.util&#39;;<br><br>export function useProductFacade(apiUrl: string) {<br>  const [filter, setFilter] = useAtom(filterAtom);<br>  const [sort, setSort] = useAtom(sortAtom);<br>  const [products] = useAtom(productsAtom);<br><br>  useFetchProducts(apiUrl);<br><br>  const updateCategory = (category: string) =&gt; {<br>    setFilter((prev) =&gt; ({ ...prev, category }));<br>  };<br><br>  const updatePriceRange = (minPrice: number, maxPrice: number) =&gt; {<br>    setFilter((prev) =&gt; ({ ...prev, priceRange: [minPrice, maxPrice] }));<br>  };<br><br>  const updateSort = (sortBy: string) =&gt; {<br>    setSort(sortBy);<br>  };<br><br>  return {<br>    products,<br>    filter,<br>    sort,<br>    updateCategory,<br>    updatePriceRange,<br>    updateSort,<br>  };<br>}</pre><p>The Facade hook provides a simple interface for the component to interact with the product data, filter, and sorting functionality. It hides the internal complexity of fetching products and managing state with <strong>Jotai</strong>.</p><p><strong>Step 4: Create the Product Listing Component</strong></p><p>Now, we’ll create the component that uses the <strong>Facade hook</strong> to display products and allow users to filter and sort them.</p><pre>// ProductList.tsx<br>import React from &#39;react&#39;;<br>import { useProductFacade } from &#39;./util/useProductFacade.util&#39;;<br><br>const ProductList: React.FC = () =&gt; {<br>  const {<br>    products,<br>    filter,<br>    sort,<br>    updateCategory,<br>    updatePriceRange,<br>    updateSort,<br>  } = useProductFacade(&#39;https://api.example.com/products&#39;);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Product Listing&lt;/h1&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;Filters&lt;/h2&gt;<br>        &lt;label&gt;<br>          Category:<br>          &lt;select<br>            value={filter.category}<br>            onChange={(e) =&gt; updateCategory(e.target.value)}<br>          &gt;<br>            &lt;option value=&quot;&quot;&gt;All&lt;/option&gt;<br>            &lt;option value=&quot;electronics&quot;&gt;Electronics&lt;/option&gt;<br>            &lt;option value=&quot;fashion&quot;&gt;Fashion&lt;/option&gt;<br>            &lt;option value=&quot;books&quot;&gt;Books&lt;/option&gt;<br>          &lt;/select&gt;<br>        &lt;/label&gt;<br>        &lt;label&gt;<br>          Price Range:<br>          &lt;input<br>            type=&quot;number&quot;<br>            value={filter.priceRange[0]}<br>            onChange={(e) =&gt; updatePriceRange(Number(e.target.value), filter.priceRange[1])}<br>          /&gt;<br>          -<br>          &lt;input<br>            type=&quot;number&quot;<br>            value={filter.priceRange[1]}<br>            onChange={(e) =&gt; updatePriceRange(filter.priceRange[0], Number(e.target.value))}<br>          /&gt;<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;Sort By&lt;/h2&gt;<br>        &lt;select value={sort} onChange={(e) =&gt; updateSort(e.target.value)}&gt;<br>          &lt;option value=&quot;relevance&quot;&gt;Relevance&lt;/option&gt;<br>          &lt;option value=&quot;price&quot;&gt;Price&lt;/option&gt;<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;Products&lt;/h2&gt;<br>        &lt;ul&gt;<br>          {products.length &gt; 0 ? (<br>            products.map((product: any) =&gt; (<br>              &lt;li key={product.id}&gt;{product.name} - ${product.price}&lt;/li&gt;<br>            ))<br>          ) : (<br>            &lt;p&gt;No products found&lt;/p&gt;<br>          )}<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductList;</pre><p>This component now interacts with the Facade to fetch and display products, as well as update the filtering and sorting state. Users can select categories, price ranges, and sort by different criteria.</p><p><strong>Benefits of the Facade Pattern in This Example</strong></p><ol><li><strong>Separation of Concerns</strong>: The component is clean and focused solely on rendering the UI. The logic for filtering, sorting, and fetching products is abstracted away in the Facade hook.</li><li><strong>Global State Management</strong>: With <strong>Jotai</strong>, the filter and sort states are global, meaning they can be shared between multiple components or even persisted for future sessions.</li><li><strong>Reusable Logic</strong>: The useProductFacade hook can be reused in other components or pages that require similar filtering or sorting logic.</li><li><strong>Modularity</strong>: The API logic and state management are modular, making it easy to add more features, such as search or additional filters.</li></ol><p><strong>Alternatives to the Facade Pattern in React</strong></p><ol><li><strong>React Context API</strong>: For managing global state or complex logic, you can use the React Context API instead of combining hooks in a Facade. However, it may lead to performance issues if not used properly (due to unnecessary re-renders).</li><li><strong>Redux or Zustand</strong>: If your application grows more complex and requires advanced state management features, using libraries like <strong>Redux</strong> or <strong>Zustand</strong> may be a more appropriate alternative. These libraries offer powerful state management tools but come with additional complexity.</li><li><strong>Composition</strong>: Instead of a Facade, you could compose your hooks directly in the component, allowing for greater flexibility. This approach is more useful when components have specific needs that don’t fit a general-purpose Facade.</li></ol><p><strong>When to Avoid the Facade Pattern</strong></p><ul><li><strong>Small Applications</strong>: If your component logic is simple and doesn’t require abstraction, the Facade pattern may add unnecessary complexity.</li><li><strong>High Flexibility Needs</strong>: If your components need fine-grained control over hook behavior, the Facade pattern might obscure too much, making it harder to customize the behavior as needed.</li></ul><p>The Facade pattern is a powerful tool for simplifying the interaction between components and multiple hooks or services in a React application. By integrating <strong>Jotai</strong> for state management, we encapsulate not only API calls and authentication but also global state management in a single, reusable interface. This approach leads to cleaner, more maintainable components and allows for easy abstraction of complex logic. However, as with any pattern, it’s important to evaluate whether the Facade pattern is necessary based on the complexity and requirements of your application.</p><p>By using <strong>React Hooks</strong> and <strong>Jotai</strong>, this implementation of the Facade pattern provides an efficient, scalable way to manage complexity while keeping components simple and easy to maintain.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165e0b505ed6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/facade-pattern-in-react-hooks-165e0b505ed6">Unlocking the Power of the Facade Pattern in React for Clean Code</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XSS Attacks in React Applications — Can We Prevent Them?]]></title>
            <link>https://blog.devgenius.io/xss-attacks-in-react-applications-can-we-prevent-them-ea7f4564ff60?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea7f4564ff60</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 12:03:31 GMT</pubDate>
            <atom:updated>2024-09-10T15:04:03.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pbLpqYx-aqadLTHQWMkCQ.png" /><figcaption>Image by <a href="https://pixabay.com/users/iffany-6128830/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8844135">Ivana Tomášková</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8844135">Pixabay</a></figcaption></figure><h3>XSS Attacks in React Applications — Can We Prevent Them?</h3><p>Cross-Site Scripting (XSS) is a <strong>security vulnerability that allows attackers to inject malicious scripts into web applications</strong>. In a React application, XSS attacks can lead to the compromise of sensitive user data, unauthorized actions, and a general breach of application integrity. <strong>Preventing XSS attacks in a React application is crucial for maintaining security</strong>. This article will explore best practices for preventing XSS in React applications.</p><ul><li><a href="https://blog.devgenius.io/comparing-validation-in-react-and-node-js-yup-vs-zod-with-typescript-ecf2e02b732a">Comparing Validation in React and Node.js: Yup vs Zod with TypeScript</a></li><li><a href="https://blog.devgenius.io/another-react-design-pattern-you-use-but-you-are-not-even-aware-of-it-82b01e5201be">Cool React Design Pattern You Use, But You Are Not Even Aware of It</a></li><li><a href="https://blog.devgenius.io/why-dry-principle-in-react-is-crucial-and-often-overlooked-especially-by-junior-developers-32acd5b750a2">Why DRY Principle in React is Crucial and Often Overlooked Especially by Junior Developers</a></li></ul><p><strong>What are XSS Attacks?</strong></p><p>XSS attacks occur when an attacker successfully injects malicious scripts into a web page. These scripts are typically JavaScript, but they can also include HTML, CSS, or other types of code. <strong>Once injected, the script is executed in the context of the victim’s browser, leading to potential data theft, session hijacking, or defacement of the website</strong>.</p><p><strong>There are three main types of XSS attacks:</strong></p><p>1. <strong>Stored XSS</strong>: The malicious script is permanently stored on the target server (e.g., in a database) and is served to users without proper sanitization.</p><p>2. <strong>Reflected XSS</strong>: The malicious script is embedded into a link, and when the user clicks on the link, the script is executed.</p><p>3. <strong>DOM-based XSS</strong>: The vulnerability exists in the client-side code (e.g., JavaScript), where data is dynamically inserted into the DOM without proper sanitization.</p><p><strong>How XSS Can Affect React Applications</strong></p><p><strong>React, by default, provides some level of protection</strong> against XSS through its built-in mechanisms like JSX escaping. <strong>However, developers must still be vigilant and follow best practices</strong> to avoid introducing vulnerabilities. <strong>For example, improperly handling user input or dynamically creating elements can expose your application to XSS risks</strong>.</p><p><strong>Best Practices for Preventing XSS in React Applications</strong></p><p>1. <strong>Automatic Escaping in JSX</strong></p><p>React automatically escapes any values embedded in JSX by default. This means that when you render user-provided content, it is automatically treated as text rather than HTML. For example:</p><pre>const userInput = &quot;&lt;img src=x onerror=alert(&#39;XSS&#39;) /&gt;&quot;;<br>return &lt;div&gt;{userInput}&lt;/div&gt;;</pre><p>The above code will render the user input as plain text, not as an HTML element, effectively neutralizing the XSS attack.</p><p>2. <strong>Avoid Using dangerouslySetInnerHTML</strong></p><p>React provides a <strong>dangerouslySetInnerHTML</strong> prop that <strong>allows you to directly set HTML content</strong> within a component. However, using this prop is highly discouraged unless absolutely necessary, as<strong> it can expose your application to XSS attacks</strong> if not handled carefully.</p><p><strong>If you must use dangerouslySetInnerHTML, ensure that the HTML content has been properly sanitized:</strong></p><pre>import DOMPurify from &#39;dompurify&#39;;<br><br>const sanitizedHTML = DOMPurify.sanitize(userInput);<br><br>return &lt;div dangerouslySetInnerHTML={{ __html: sanitizedHTML }} /&gt;;</pre><p>3. <strong>Sanitize User Input</strong></p><p>Always <strong>sanitize user input</strong> before rendering it in the UI or using it within the application logic. Libraries like <strong>DOMPurify</strong> or <strong>xss</strong> can help remove or encode potentially harmful scripts.</p><pre>import DOMPurify from &#39;dompurify&#39;;<br><br>const sanitizedInput = DOMPurify.sanitize(userInput);<br><br>return &lt;div&gt;{sanitizedInput}&lt;/div&gt;;</pre><p>4. <strong>Validate and Encode Data on the Server</strong></p><p>Even though this article focuses on the React front end, <strong>it’s important to validate and sanitize data on the server side as well</strong>. This ensures that even if malicious data somehow gets through the front-end defenses, it won’t compromise your application.</p><p>On the server, validate incoming data for expected formats, lengths, and types, and encode data before storing it in the database or sending it back to the client.</p><p>5. <strong>Use Content Security Policy (CSP)</strong></p><p><strong>Content Security Policy (CSP)</strong> is an HTTP header that helps prevent XSS attacks by specifying which sources of content are allowed to be loaded in your application. By defining a strict CSP, you can significantly reduce the risk of XSS.</p><p>Example of a simple CSP:</p><pre>Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39; https://trustedscripts.example.com; object-src &#39;none&#39;;</pre><p><strong>This policy allows scripts only from your domain and a trusted external source</strong>, while disallowing plugins and other potentially risky content.</p><p>6. <strong>Avoid Using Inline Event Handlers</strong></p><p><strong>Avoid using inline event handlers</strong> like onClick, onMouseOver, etc., that are embedded directly within the HTML. <strong>Instead, bind event handlers within the React component</strong>. Inline handlers can be a vector for XSS if user input is injected into these attributes.</p><p><strong>Unsafe:</strong></p><pre>&lt;button onClick=&quot;handleClick()&quot;&gt;Click Me&lt;/button&gt;</pre><p><strong>Safe:</strong></p><pre>&lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;</pre><p>7. <strong>Keep React and Dependencies Updated</strong></p><p>Always keep React and its dependencies up to date. <strong>Security vulnerabilities are often discovered and patched in newer versions of libraries</strong>. Regularly updating your dependencies ensures you benefit from the latest security fixes.</p><p>8. <strong>Use Security Linters</strong></p><p><strong>Incorporate security linters into your development process to catch potential XSS vulnerabilities.</strong> Linters like ESLint with plugins such as eslint-plugin-security can help identify unsafe coding practices that might lead to XSS.</p><p>9. <strong>Educate Your Team</strong></p><p>Educate your development team about XSS and other security threats. <strong>Awareness is one of the best defenses against introducing vulnerabilities into your application</strong>. Regular security training and code reviews can help prevent common mistakes that lead to XSS.</p><p>Preventing XSS attacks in React applications requires a combination of React’s built-in protections, secure coding practices, and the use of external tools for sanitization and validation. <strong>By following the best practices outlined in this article, you can significantly reduce the risk of XSS attacks and create a more secure React application</strong>. Always stay updated on security trends and continue to educate your team to maintain a robust security posture.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea7f4564ff60" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/xss-attacks-in-react-applications-can-we-prevent-them-ea7f4564ff60">XSS Attacks in React Applications — Can We Prevent Them?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React’s useReducer: Do We Even Need It, or Is It Better to Use Redux or Jotai?]]></title>
            <link>https://javascript.plainenglish.io/reacts-usereducer-do-we-even-need-it-or-is-it-better-to-use-redux-or-jotai-4433976683d6?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4433976683d6</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 12:14:28 GMT</pubDate>
            <atom:updated>2024-09-05T12:25:47.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlNr_c2mMgy7XV4FYwA5PQ.jpeg" /><figcaption><a href="https://www.pexels.com/photo/man-sitting-in-front-of-three-computers-4974915/">Photo by Olia Danilevich</a></figcaption></figure><p>When managing state in React applications, we often face the dilemma of choosing the right tools. <strong>Among the built-in options, useReducer doesn’t stand out as a popular choice for managing complex state logic. Probably, because with modern state management libraries like Zustand, Jotai</strong>, <strong>and the combined power of useContext</strong>, the necessity of useReducer is usually questioned. In this article, we will take a deep dive into useReducer, its use cases, and whether it’s still essential in the era of modern state management tools.</p><p><a href="https://medium.com/@maciejpoppek/state-management-with-jotai-react-and-typescript-ready-library-a40ac967ac3e">State Management with Jotai — React and TypeScript ready library — World of Atoms</a></p><p>useReducer is a React hook that serves as an alternative to useState for managing state, especially when dealing with complex logic. <strong>Unlike useState, which handles individual pieces of state, useReducer works well when the state management involves multiple related variables</strong> or when the next state depends on the previous state.</p><p><strong>Basic Syntax</strong></p><p>Here’s how you can use useReducer:</p><pre>const [state, dispatch] = useReducer(reducer, initialState);</pre><ul><li><strong>reducer</strong>: A function that takes the current state and an action, then returns the new state.</li><li><strong>initialState</strong>: The initial value for the state.</li></ul><p><strong>Example of useReducer</strong></p><p>Consider a simple counter using useReducer:</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>type State = { count: number };<br>type Action = { type: &#39;increment&#39; | &#39;decrement&#39; };<br><br>const initialState: State = { count: 0 };<br><br>function reducer(state: State, action: Action): State {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;decrement&#39;:<br>      return { count: state.count - 1 };<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>export function Counter() {<br>  const [state, dispatch] = useReducer(reducer, initialState);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {state.count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39; })}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the <strong>reducer function handles two actions: increment and decrement</strong>. The dispatch function is used to trigger these actions, which in turn update the state.</p><p><strong>Why Use useReducer?</strong></p><p><strong>1. Complex State Logic</strong></p><p>useReducer excels when dealing with <strong>complex state logic, where multiple state variables interact or where the next state depends on the previous one</strong>. This is especially useful in scenarios like forms with multiple fields, complex UI components, or when implementing undo-redo functionality.</p><p><strong>2. Predictable State Transitions</strong></p><p>State transitions in useReducer are explicit and <strong>predictable, as all state updates go through the reducer function</strong>. This makes the code easier to reason about, trace, and debug.</p><p><strong>3. Testability</strong></p><p><strong>Reducers are pure functions, meaning they have no side effects</strong>. This makes them easy to test in isolation, ensuring your state management logic is robust and reliable.</p><p><strong>Do We Even Need useReducer?</strong></p><p>Despite its advantages, there are scenarios where useReducer may not be necessary. <strong>Modern state management libraries like Zustand, Jotai, and even useContext can sometimes be better suited</strong> for managing global or shared state across components.</p><p><strong>Comparing useReducer with useContext</strong></p><p>useContext is often paired with useReducer to manage global state across your application. Here’s an example:</p><pre>import React, { createContext, useContext, useReducer } from &#39;react&#39;;<br><br>type State = { count: number };<br>type Action = { type: &#39;increment&#39; | &#39;decrement&#39; };<br><br>const initialState: State = { count: 0 };<br><br>const CounterContext = createContext&lt;{ state: State; dispatch: React.Dispatch&lt;Action&gt; } | undefined&gt;(undefined);<br><br>function reducer(state: State, action: Action): State {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;decrement&#39;:<br>      return { count: state.count - 1 };<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>export function CounterProvider({ children }: { children: React.ReactNode }) {<br>  const [state, dispatch] = useReducer(reducer, initialState);<br>  return (<br>    &lt;CounterContext.Provider value={{ state, dispatch }}&gt;<br>      {children}<br>    &lt;/CounterContext.Provider&gt;<br>  );<br>}<br><br>export function useCounter() {<br>  const context = useContext(CounterContext);<br>  if (!context) {<br>    throw new Error(&#39;useCounter must be used within a CounterProvider&#39;);<br>  }<br>  return context;<br>}</pre><p>This example demonstrates how useContext can be combined with useReducer to create a global state that can be accessed by any component within the provider. <strong>However, this setup can become unwieldy as the application grows.</strong></p><p><strong>Zustand: A Modern Alternative</strong></p><p>Zustand is a lightweight, scalable state management library that simplifies global state management. <strong>It’s easy to set up and works well with TypeScript.</strong></p><pre>import create from &#39;zustand&#39;;<br><br>type State = {<br>  count: number;<br>  increment: () =&gt; void;<br>  decrement: () =&gt; void;<br>};<br><br>const useStore = create&lt;State&gt;((set) =&gt; ({<br>  count: 0,<br>  increment: () =&gt; set((state) =&gt; ({ count: state.count + 1 })),<br>  decrement: () =&gt; set((state) =&gt; ({ count: state.count - 1 })),<br>}));<br><br>export function Counter() {<br>  const { count, increment, decrement } = useStore();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;+&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Zustand eliminates the need for boilerplate code associated</strong> with setting up contexts and reducers, offering a more streamlined approach to state management.</p><p><strong>Jotai: A Modern, Atomic Approach</strong></p><p>Jotai is another state management library that offers a different approach. <strong>It uses atoms to represent pieces of state, allowing for fine-grained control and scalability.</strong></p><p>Here’s an example using Jotai:</p><pre>import { atom, useAtom } from &#39;jotai&#39;;<br><br>const countAtom = atom(0);<br><br>export function Counter() {<br>  const [count, setCount] = useAtom(countAtom);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount((c) =&gt; c + 1)}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount((c) =&gt; c - 1)}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>With Jotai, each piece of state is an atom, which can be shared and combined in a flexible manner. <strong>This approach allows for better scalability, as you can manage state at a very granular level without the complexity of a global state.</strong></p><p><strong>Redux: The OG State Management Library</strong></p><p>Redux is a well-established state management library, still relevant for complex applications. With Redux Toolkit, the API has become more modern and easier to use with TypeScript.</p><pre>import { configureStore, createSlice, PayloadAction } from &#39;@reduxjs/toolkit&#39;;<br>import { Provider, useDispatch, useSelector } from &#39;react-redux&#39;;<br><br>type CounterState = {<br>  count: number;<br>};<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState: { count: 0 } as CounterState,<br>  reducers: {<br>    increment(state) {<br>      state.count += 1;<br>    },<br>    decrement(state) {<br>      state.count -= 1;<br>    },<br>  },<br>});<br><br>const store = configureStore({<br>  reducer: {<br>    counter: counterSlice.reducer,<br>  },<br>});<br><br>export function Counter() {<br>  const count = useSelector((state: { counter: CounterState }) =&gt; state.counter.count);<br>  const dispatch = useDispatch();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch(counterSlice.actions.increment())}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch(counterSlice.actions.decrement())}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export function App() {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;Counter /&gt;<br>    &lt;/Provider&gt;<br>  );<br>}</pre><p>Redux, particularly with Redux Toolkit, remains a powerful choice for scalable state management solution.</p><p><strong>Is useReducer Even Necessary?</strong></p><p>In modern React applications alternatives like Zustand, Jotai, or even Redux with Redux Toolkit offer compelling features that might make useReducer feel redundant. <strong>These libraries provide more flexibility, better performance, and easier scalability, particularly for global state management.</strong></p><p>Ultimately, the choice between useReducer, useContext, or modern state management libraries like Zustand and Jotai depends on your application’s needs, complexity, and your team’s familiarity with these tools. While useReducer remains a valuable tool in the React ecosystem, it’s essential to evaluate whether it’s the best fit for your specific use case or if a more modern solution might serve you better.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4433976683d6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/reacts-usereducer-do-we-even-need-it-or-is-it-better-to-use-redux-or-jotai-4433976683d6">React’s useReducer: Do We Even Need It, or Is It Better to Use Redux or Jotai?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cool React Design Pattern You Use, But You Are Not Even Aware of It]]></title>
            <link>https://blog.devgenius.io/another-react-design-pattern-you-use-but-you-are-not-even-aware-of-it-82b01e5201be?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82b01e5201be</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 12:11:12 GMT</pubDate>
            <atom:updated>2024-08-27T03:44:32.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3KwmuwJ-TbYRwEHRPWPsQ.jpeg" /><figcaption><a href="https://www.freepik.com/free-photo/programming-background-with-person-working-with-codes-computer_38669465.htm#fromView=search&amp;page=1&amp;position=12&amp;uuid=f33b4667-0c6e-467c-904c-d55a1a0200c5">Image by freepik</a></figcaption></figure><p><strong>Links to previous articles about React Design Patterns:</strong></p><ul><li><strong>Container-Presentional Pattern:<br></strong> <a href="https://medium.com/@maciejpoppek/the-most-widely-used-pattern-in-react-the-container-presentational-pattern-16c8133caf1a">https://medium.com/@maciejpoppek/the-most-widely-used-pattern-in-react-the-container-presentational-pattern-16c8133caf1a</a></li><li><strong>Factory Pattern:</strong> <br><a href="https://medium.com/@maciejpoppek/the-react-design-pattern-youre-using-without-even-realizing-it-e85385fd354d">https://medium.com/@maciejpoppek/the-react-design-pattern-youre-using-without-even-realizing-it-e85385fd354d</a></li></ul><p>So, the design pattern we will discuss is the <strong>controlled-uncontrolled pattern</strong>. Understanding this pattern is crucial for designing efficient, well-structured, and maintainable applications.</p><p><strong>What the heck are Controlled Components?</strong></p><p>Controlled components are React components that <strong>rely on React state to manage their data</strong>. The form data in these components is controlled by the component’s state, and any change to the form input values is handled by React’s state management.</p><p>In a <strong>controlled component</strong>, the input form <strong>element’s value is controlled by React</strong>, and any user input is processed by event handlers such as onChange.</p><p><strong>Example of a Controlled Component</strong></p><pre>import React, { useState } from &quot;react&quot;;<br><br>const ControlledInput: React.FC = () =&gt; {<br>  const [inputValue, setInputValue] = useState&lt;string&gt;(&quot;&quot;);<br><br>  const handleChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    setInputValue(event.target.value);<br>  };<br><br>  const handleSubmit = (event: React.FormEvent) =&gt; {<br>    event.preventDefault();<br>    console.log(&quot;Submitted value:&quot;, inputValue);<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;label&gt;<br>        Controlled Input:<br>        &lt;input type=&quot;text&quot; value={inputValue} onChange={handleChange} /&gt;<br>      &lt;/label&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default ControlledInput;</pre><p>In this example:</p><ul><li>The inputValue state variable <strong>stores the current value</strong> of the input field.</li><li>The onChange event handler <strong>updates the state</strong> whenever the user types something.</li><li>The input’s value prop is tied to inputValue, <strong>making this a controlled component</strong> managed by its parent component (in this case, the same component, but it could be a parent component in a larger application).</li></ul><p><strong>What are Uncontrolled Components?</strong></p><p>Uncontrolled components, on the other hand, <strong>do not store form data in React’s state</strong>. <strong>Instead, they rely on the DOM </strong>to manage the form data. In these components, form input elements use a ref to access the DOM elements directly.</p><p>Uncontrolled components are<strong> useful</strong> <strong>when</strong> you need to <strong>integrate with non-React code</strong> or if you need to <strong>optimize performance</strong> by <strong>avoiding</strong> <strong>unnecessary re-renders</strong>.</p><p><strong>Example of an Uncontrolled Component</strong></p><pre>import React, { useRef } from &quot;react&quot;;<br><br>const UncontrolledInput: React.FC = () =&gt; {<br>  const inputRef = useRef&lt;HTMLInputElement&gt;(null);<br><br>  const handleSubmit = (event: React.FormEvent) =&gt; {<br>    event.preventDefault();<br>    if (inputRef.current) {<br>      console.log(&quot;Submitted value:&quot;, inputRef.current.value);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;label&gt;<br>        Uncontrolled Input:<br>        &lt;input type=&quot;text&quot; ref={inputRef} /&gt;<br>      &lt;/label&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default UncontrolledInput;</pre><p>In this example:</p><ul><li>The inputRef is used to <strong>directly access the DOM</strong> element.</li><li>The input field’s <strong>value is not managed by React state</strong> but can still be accessed when needed, such as during form submission.</li></ul><p><strong>Key Differences Between Controlled and Uncontrolled Components</strong></p><p>1. <strong>State Management</strong>:</p><ul><li><strong>Controlled Components</strong>: The form data is managed via React state, typically by a parent component. The parent component controls the state of the input by passing down the value and a change handler as props.</li><li><strong>Uncontrolled Components</strong>: The form data is managed by the component itself, without any control from the parent component. The component uses refs to access the DOM directly.</li></ul><p>2. <strong>Re-renders</strong>:</p><ul><li><strong>Controlled Components</strong>: Input changes cause re-renders as the state updates in the parent component.</li><li><strong>Uncontrolled Components</strong>: Input changes do not cause re-renders since the value is not in React state.</li></ul><p>3. <strong>Default Values</strong>:</p><ul><li><strong>Controlled Components</strong>: The initial value is set using state (useState).</li><li><strong>Uncontrolled Components</strong>: The initial value is set using the defaultValue prop or directly in the DOM.</li></ul><p>4. <strong>Validation</strong>:</p><ul><li><strong>Controlled Components</strong>: Validation is easier to implement as the form data is stored in state and controlled by the parent component.</li><li><strong>Uncontrolled Components</strong>: Validation requires manual DOM access and is typically more cumbersome.</li></ul><p><strong>When to Use Controlled vs. Uncontrolled Components</strong></p><p><strong>Use Controlled Components</strong>:</p><ul><li>When you need to <strong>enforce validation and ensure that the UI is in sync</strong> with your data model.</li><li>When dealing with <strong>complex forms</strong> where the form data needs to be manipulated or validated frequently.</li><li>When you want to <strong>control the behavior of the form</strong> inputs tightly (e.g., disabling a button until all fields are valid).</li></ul><p><strong>Use Uncontrolled Components</strong>:</p><ul><li>When integrating with <strong>third-party libraries</strong> <strong>or non-React code</strong>.</li><li>When <strong>building simple forms</strong> where performance is a concern, and you want to avoid re-renders.</li><li>When the <strong>form’s data doesn’t need to be immediately accessible</strong> to other parts of your React component.</li></ul><p><strong>Both controlled and uncontrolled components have their use cases in React applications</strong>. Controlled components offer more power and flexibility by integrating tightly with React’s state management, while uncontrolled components provide a more straightforward and performant way to handle form data, especially in simpler scenarios.</p><p>By understanding and leveraging these patterns, you can build more efficient and maintainable React applications, particularly when using TypeScript, which ensures type safety and reduces potential runtime errors. <strong>Choose the pattern that best fits your specific use case</strong> to create clean, effective, and scalable user interfaces!</p><h4><strong>ONE MORE THING… 🍏 LET’S PRACTISE WHAT WE HAVE JUST LEARNED BY REFACTORING COMPONENTS!</strong></h4><p>Let’s consider a scenario where a parent component manages the state of a form, and a child component renders an input field. Initially, the child component is implemented as an uncontrolled component. We’ll refactor it to a controlled component to follow best practices.</p><p><strong>Before Refactor: Uncontrolled Child Component</strong></p><p>In this setup, the child component uses a ref to manage the input value, making it an uncontrolled component:</p><p><strong>Parent Component (Before Refactor)</strong></p><pre>import React, { useState } from &quot;react&quot;;<br>import UncontrolledChild from &quot;./UncontrolledChild&quot;;<br><br>const ParentComponent: React.FC = () =&gt; {<br>  const [name, setName] = useState&lt;string&gt;(&quot;&quot;);<br><br>  const handleChange = (newName: string) =&gt; {<br>    setName(newName);<br>  };<br><br>  const handleSubmit = () =&gt; {<br>    console.log(&quot;Name from child:&quot;, name);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;UncontrolledChild onNameChange={handleChange} /&gt;<br>      &lt;button onClick={handleSubmit}&gt;Submit&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ParentComponent;</pre><p><strong>Child Component (Before Refactor)</strong></p><pre>import React, { useRef } from &quot;react&quot;;<br><br>interface UncontrolledChildProps {<br>  onNameChange: (name: string) =&gt; void;<br>}<br><br>const UncontrolledChild: React.FC&lt;UncontrolledChildProps&gt; = ({ onNameChange }) =&gt; {<br>  const inputRef = useRef&lt;HTMLInputElement&gt;(null);<br><br>  const handleInputChange = () =&gt; {<br>    if (inputRef.current) {<br>      onNameChange(inputRef.current.value);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;<br>        Name:<br>        &lt;input type=&quot;text&quot; ref={inputRef} onChange={handleInputChange} /&gt;<br>      &lt;/label&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UncontrolledChild;</pre><p><strong>After Refactor: Controlled Child Component with Centralized Input Handling</strong></p><p><strong>We’ll refactor</strong> the code so that <strong>the parent component</strong> controls the input value. The <strong>handleInputChange function will be centralized</strong> in the parent component and <strong>passed down to the child component</strong>. We’ll also use <strong>useCallback to optimize performance</strong> by preventing unnecessary re-renders.</p><p><strong>Parent Component (After Refactor)</strong></p><pre>import React, { useState, useCallback } from &quot;react&quot;;<br>import ControlledChild from &quot;./ControlledChild&quot;;<br><br>const ParentComponent: React.FC = () =&gt; {<br>  const [formData, setFormData] = useState&lt;{ name: string; email: string }&gt;({<br>    name: &quot;&quot;,<br>    email: &quot;&quot;,<br>  });<br><br>  const handleInputChange = useCallback(<br>    (field: keyof typeof formData, value: string) =&gt; {<br>      setFormData((prevData) =&gt; ({<br>        ...prevData,<br>        [field]: value,<br>      }));<br>    },<br>    []<br>  );<br><br>  const handleSubmit = () =&gt; {<br>    console.log(&quot;Form Data:&quot;, formData);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ControlledChild<br>        label=&quot;Name&quot;<br>        value={formData.name}<br>        onInputChange={(value) =&gt; handleInputChange(&quot;name&quot;, value)}<br>      /&gt;<br>      &lt;ControlledChild<br>        label=&quot;Email&quot;<br>        value={formData.email}<br>        onInputChange={(value) =&gt; handleInputChange(&quot;email&quot;, value)}<br>      /&gt;<br>      &lt;button onClick={handleSubmit}&gt;Submit&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ParentComponent;</pre><p><strong>Child Component (After Refactor)</strong></p><pre>import React from &quot;react&quot;;<br><br>interface ControlledChildProps {<br>  label: string;<br>  value: string;<br>  onInputChange: (value: string) =&gt; void;<br>}<br><br>const ControlledChild: React.FC&lt;ControlledChildProps&gt; = ({<br>  label,<br>  value,<br>  onInputChange,<br>}) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;<br>        {label}:<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={value}<br>          onChange={(e) =&gt; onInputChange(e.target.value)}<br>        /&gt;<br>      &lt;/label&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ControlledChild;</pre><p><strong>Benefits of the Refactored Approach</strong></p><ol><li><strong>Centralized Logic</strong>: The input handling logic is now centralized in the parent component, making the code easier to maintain and understand.</li><li><strong>Reusability</strong>: The handleInputChange function is reusable for multiple input fields, reducing code duplication and increasing scalability.</li><li><strong>Optimization</strong>: Using useCallback optimizes performance by preventing unnecessary re-renders, particularly when passing down the input handler as a prop.</li><li><strong>Simplified Child Components</strong>: The child components are now stateless and purely presentational, making them easier to test and reuse.</li></ol><p>By refactoring the child component to be controlled and centralizing the input handling logic in the parent component, we improve the maintainability and scalability of our React application. This approach ensures that the form data is always in sync with the component state, leading to a predictable and well-organized codebase.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82b01e5201be" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/another-react-design-pattern-you-use-but-you-are-not-even-aware-of-it-82b01e5201be">Cool React Design Pattern You Use, But You Are Not Even Aware of It</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Updates to JavaScript Since ES6 That Have Changed the Way We Use JavaScript Plus Bonus]]></title>
            <link>https://blog.devgenius.io/6-updates-to-javascript-since-es6-that-have-changed-the-way-we-use-javascript-plus-bonus-b2fb13bf53c6?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2fb13bf53c6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 10:10:07 GMT</pubDate>
            <atom:updated>2024-08-26T19:48:26.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOt0txkfaO0Vwmyh74L7MQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/vilkasss-35420724/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8640893">Vilius Kukanauskas</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8640893">Pixabay</a></figcaption></figure><p><strong>JavaScript</strong> has been an essential part of web development since its inception, and its evolution has been nothing short of remarkable. The introduction of <strong>ECMAScript 6 (ES6)</strong> in <strong>2015</strong> was a watershed moment that brought significant changes to the language. However, JavaScript didn’t stop evolving there. In the years since <strong>ES6</strong>, several key updates have transformed the way developers write and think about JavaScript. Here are <strong>six updates since ES6 </strong>that have had a profound impact on the language and its usage.</p><p><strong>1. Async/Await (ES8/ES2017)</strong></p><p>One of the most transformative updates to JavaScript came with the introduction of async/await in <strong>ES8 (ECMAScript 2017)</strong>. Before this, developers had to rely on callbacks or promises to handle asynchronous operations, leading to complex and often unreadable code — commonly known as “<strong>callback hell</strong>.”</p><p><strong>async/await simplifies asynchronous code, making it look and behave more like synchronous code.</strong> By using the async keyword before a function and await before a promise, developers can write code that’s easier to read, understand, and maintain. This syntactic sugar has made handling asynchronous operations much more intuitive and has significantly reduced the cognitive load on developers.</p><pre>async function fetchData() {<br>  try {<br>    let response = await fetch(&#39;https://api.example.com/data&#39;);<br>    let data = await response.json();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(&#39;Error fetching data:&#39;, error);<br>  }<br>}</pre><p><strong>2. Optional Chaining (ES11/ES2020)</strong></p><p>Introduced in <strong>ES11 (ECMAScript 2020)</strong>, <strong>Optional Chaining</strong> (?.) is a feature that has greatly enhanced how developers handle objects, especially when dealing with deeply nested properties. Before this, checking if an object’s property existed required cumbersome and repetitive code, often using logical AND (<strong>&amp;&amp;</strong>) operators or if statements.</p><p><strong>Optional Chaining</strong> allows developers to safely access deeply nested properties without having to manually check each level for null or undefined. If any part of the chain is null or <strong>undefined</strong>, the expression short-circuits and returns undefined instead of throwing an error.</p><pre>const user = {<br>  name: &#39;Alice&#39;,<br>  address: {<br>    city: &#39;Wonderland&#39;<br>  }<br>};<br><br>console.log(user?.address?.city);<br>// Output: &#39;Wonderland&#39;<br>console.log(user?.contact?.phone);<br>// Output: undefined</pre><p><strong>3. Nullish Coalescing (ES11/ES2020)</strong></p><p>Another game-changing feature introduced in <strong>ES11</strong> is <strong>Nullish Coalescing</strong> (<strong>??</strong>). This operator provides a more refined way to handle null or undefined values. Before its introduction, developers often used the logical OR (<strong>||</strong>) operator to assign default values, which could lead to unintended behavior if <strong>false</strong>, <strong>0</strong>, or ‘’ were considered valid values.</p><p><strong>Nullish Coalescing</strong> ensures that only null or undefined trigger the fallback value, allowing <strong>false</strong>, <strong>0</strong>, and other <strong>falsy values</strong> to be used as intended.</p><pre>let userName = null;<br>let displayName = userName ?? &#39;Guest&#39;;<br>console.log(displayName);<br>// Output: &#39;Guest&#39;<br><br>let userAge = 0;<br>let age = userAge ?? 18;<br>console.log(age);<br>// Output: 0</pre><p><strong>4. Dynamic Imports (ES10/ES2019)</strong></p><p>Dynamic Imports, introduced in <strong>ES10 (ECMAScript 2019)</strong>, have revolutionized how JavaScript modules are handled. <strong>Before dynamic imports, all modules had to be imported statically at the beginning of a file. </strong>This approach often led to unnecessary loading of modules, increasing the initial load time of web applications.</p><p>With dynamic imports, <strong>developers can now load modules asynchronously and on demand</strong>, only when they are needed. This can significantly <strong>improve the performance of web applications</strong>, especially large ones, by reducing the initial bundle size and enabling more efficient code splitting.</p><pre>async function loadModule() {<br>  if (condition) {<br>    const { someFunction } = await import(&#39;./someModule.js&#39;);<br>    someFunction();<br>  }<br>}</pre><p><strong>5. BigInt (ES11/ES2020)</strong></p><p>JavaScript has long struggled with handling very large integers due to its use of the 64-bit floating-point format, which only supports safe integers up to 2^{53} — 1. The introduction of <strong>BigInt</strong> in <strong>ES11</strong> provides a new numeric primitive that allows developers to work with arbitrarily large integers.</p><p><strong>BigInt solves the problem of integer overflow in JavaScript</strong>, making it possible to perform calculations on large numbers without losing precision. <strong>This feature is particularly useful in domains like cryptography, scientific computing, and financial applications where precision is critical.</strong></p><pre>const maxSafeInteger = BigInt(Number.MAX_SAFE_INTEGER);<br>const largeNumber = maxSafeInteger + 1n;<br>console.log(largeNumber);<br>// Output: 9007199254740992n</pre><p><strong>6. Logical Assignment Operators (ES12/ES2021)</strong></p><p>Introduced in <strong>ES12</strong> (<strong>ECMAScript 2021</strong>), <strong>Logical Assignment Operators</strong> combine logical operations with assignment, streamlining certain coding patterns. These operators <strong>&amp;&amp;=, ||=, and ??=</strong> allow developers to write more concise code by combining common logical operations with assignment into a single, compact expression.</p><p>Before these operators, developers often had to write repetitive code to assign values based on conditions. <strong>The Logical Assignment Operators</strong> make these patterns more efficient, reducing the amount of boilerplate code and enhancing readability.</p><pre>let config = {<br>  isEnabled: true,<br>  timeout: 0,<br>};<br><br>// &amp;&amp;= (Logical AND Assignment)<br>config.isEnabled &amp;&amp;= false;<br>// Equivalent to: if (config.isEnabled) { config.isEnabled = false; }<br>console.log(config.isEnabled);<br>// Output: false<br><br>// ||= (Logical OR Assignment)<br>config.timeout ||= 3000;<br>// Equivalent to: if (!config.timeout) { config.timeout = 3000; }<br>console.log(config.timeout);<br>// Output: 3000<br><br>// ??= (Nullish Coalescing Assignment)<br>config.maxRetries ??= 5;<br>// Equivalent to: if (config.maxRetries === null || config.maxRetries === undefined) { config.maxRetries = 5; }<br>console.log(config.maxRetries);<br>// Output: 5</pre><p><strong>BONUS: Array findLast and findLastIndex Methods (ES13/ES2022)</strong></p><p><strong>ES13 (ECMAScript 2022)</strong> introduced two new methods for arrays: <strong>findLast</strong> and <strong>findLastIndex</strong>. These methods are similar to the existing find and findIndex methods but start the search from the end of the array.</p><p>Before the introduction of these methods, developers had to reverse the array or manually iterate from the end to find the last occurrence of an element matching a condition. <strong>findLast</strong> and <strong>findLastIndex</strong> simplify this task, making the code more intuitive and reducing the potential for errors in handling array traversal.</p><pre>// Example with findLast and findLastIndex<br>const numbers = [5, 12, 8, 130, 44, 130];<br><br>// findLast: Finds the last element greater than 100<br>const lastLargeNumber = numbers.findLast(num =&gt; num &gt; 100);<br>console.log(lastLargeNumber); // Output: 130<br><br>// findLastIndex: Finds the last index of an element greater than 100<br>const lastLargeNumberIndex = numbers.findLastIndex(num =&gt; num &gt; 100);<br>console.log(lastLargeNumberIndex); // Output: 5</pre><p>These methods are especially useful when working with arrays where the last matching element is more relevant than the first, providing a straightforward approach to accessing it without needing to reverse the array or use more complex logic.</p><p>…</p><p>Since the landmark release of ES6, <strong>JavaScript has continued to evolve</strong>, introducing features that have dramatically changed how developers write and manage code. From making asynchronous programming more manageable with <strong>async/await</strong> to handling large numbers with <strong>BigInt</strong>, these updates have made JavaScript more powerful, efficient, and easier to work with. As the language continues to evolve, developers can expect even more innovations that will further refine and enhance their coding experience.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2fb13bf53c6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/6-updates-to-javascript-since-es6-that-have-changed-the-way-we-use-javascript-plus-bonus-b2fb13bf53c6">6 Updates to JavaScript Since ES6 That Have Changed the Way We Use JavaScript Plus Bonus</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The React Design Pattern You’re Using Without Even Realizing It]]></title>
            <link>https://blog.devgenius.io/the-react-design-pattern-youre-using-without-even-realizing-it-e85385fd354d?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85385fd354d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 13:30:44 GMT</pubDate>
            <atom:updated>2024-08-20T04:25:06.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQlFY73YVSXgQO6J0GyzSg.jpeg" /></figure><p>In the world of <strong>software design</strong>, <strong>design patterns</strong> play a crucial role in creating <strong>scalable</strong>, <strong>maintainable</strong>, and <strong>understandable codebases</strong>. Among these, the <strong>Factory Pattern</strong> is a common but often unrecognized pattern that developers frequently use, especially in React applications. <strong>The irony is that many developers use this pattern unknowingly</strong>, and when confronted with design pattern questions during an interview, they may struggle to explain their own code.</p><p>This article aims to demystify the <strong>Factory Pattern</strong> in the context of React development, with <strong>TypeScript</strong> as the language of choice. By the end, you’ll understand how you may already be using the Factory Pattern and how to consciously apply it to improve your code.</p><h4><strong>What is the Factory Pattern?</strong></h4><p>The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. <strong>The essence of this pattern is that it abstracts the process of object creation, deferring it to specific factory methods.</strong></p><p>In simpler terms, rather than instantiating objects directly, you delegate this responsibility to a factory method that knows exactly how to create the necessary object.</p><h4><strong>Factory Pattern in React</strong></h4><p>In React, especially when working with UI components, we often need to render different components based on certain conditions. This is where the Factory Pattern subtly enters the scene. <strong>Instead of directly rendering components</strong> within your render method (or functional component), <strong>you delegate this responsibility to a function</strong> that decides which component to create based on input parameters.</p><h4><strong>Example: A Button Factory in React with TypeScript</strong></h4><p>Imagine you’re building a UI library that needs different types of buttons: a primary button, a secondary button, and a danger button. Each button has its own styling and behavior. <strong>Rather than scattering conditional logic across your components, you can use the Factory Pattern to encapsulate this logic.</strong></p><p>Here’s how you might implement this:</p><p><strong>Step 1: Define Button Types and Props</strong></p><pre>type ButtonType = &#39;primary&#39; | &#39;secondary&#39; | &#39;danger&#39;;<br><br>interface ButtonProps {<br>  label: string;<br>  onClick: () =&gt; void;<br>}</pre><p>Here, ButtonType is still a union type that specifies the different kinds of buttons. The ButtonProps interface includes a type prop to determine the button style, along with label and onClick for its functionality.</p><p><strong>Step 2: Create the Button Component</strong></p><pre>import React from &#39;react&#39;;<br><br>const Button: React.FC&lt;ButtonProps&gt; = ({ type, label, onClick }) =&gt; {<br>  const getButtonStyle = (type: ButtonType): React.CSSProperties =&gt; {<br>    switch (type) {<br>      case &#39;primary&#39;:<br>        return { backgroundColor: &#39;blue&#39;, color: &#39;white&#39; };<br>      case &#39;secondary&#39;:<br>        return { backgroundColor: &#39;gray&#39;, color: &#39;black&#39; };<br>      case &#39;danger&#39;:<br>        return { backgroundColor: &#39;red&#39;, color: &#39;white&#39; };<br>      default:<br>        return {};<br>    }<br>  };<br><br>  return (<br>    &lt;button style={getButtonStyle(type)} onClick={onClick}&gt;<br>      {label}<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default Button;</pre><p>In this implementation, the Button component is a <strong>single, reusable component</strong>. It uses the type prop to determine which style to apply. The <strong>getButtonStyle function encapsulates the style logic</strong>, making the component easy to extend if new button types are added.</p><p><strong>Step 3: Using the Button Component</strong></p><pre>const App: React.FC = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Button type=&quot;primary&quot; label=&quot;Primary Button&quot; onClick={() =&gt; alert(&#39;Primary Clicked!&#39;)} /&gt;<br>      &lt;Button type=&quot;secondary&quot; label=&quot;Secondary Button&quot; onClick={() =&gt; alert(&#39;Secondary Clicked!&#39;)} /&gt;<br>      &lt;Button type=&quot;danger&quot; label=&quot;Danger Button&quot; onClick={() =&gt; alert(&#39;Danger Clicked!&#39;)} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In the App component, you can now use the &lt;Button&gt; component directly, passing the appropriate type prop to adjust its appearance.</p><h4><strong>Why Use the Factory Pattern in React?</strong></h4><ol><li><strong>Centralized Component Creation</strong>: By using the Factory Pattern, you centralize the logic for component creation. This makes it easier to manage and update the logic when new types are added or existing ones are changed.</li><li><strong>Cleaner Code</strong>: Instead of cluttering your components with conditionals to decide which UI elements to render, the factory handles this, leading to cleaner and more readable code.</li><li><strong>Scalability</strong>: As your application grows, you can easily extend the factory to create more components without modifying the existing logic.</li><li><strong>Testability</strong>: With a factory method, you can easily mock or stub out specific component creation in your tests, leading to more robust unit testing.</li></ol><p>…</p><p>The <strong>Factory Pattern</strong> is a <strong>powerful tool in React development</strong>, particularly when <strong>dealing with UI components</strong> that vary based on certain conditions. While <strong>many developers</strong> may <strong>unknowingly use</strong> <strong>this</strong> <strong>pattern</strong>, recognizing it can help you write more maintainable, scalable, and testable code. Additionally, having an <strong>understanding of this pattern</strong> <strong>can give you a competitive edge in</strong> <strong>technical interviews</strong>, as you’ll be able to articulate your design decisions more effectively.</p><p>Next time you’re building a React component, consider whether the <strong>Factory Pattern</strong> <strong>might help you organize your code</strong> more effectively. Chances are, you’ve already been using it without even knowing!</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><p>Photo by <a href="https://www.pexels.com/photo/conceptual-photo-of-word-play-spelled-by-wooden-blocks-1275235/">Suzy Hazelwood</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85385fd354d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/the-react-design-pattern-youre-using-without-even-realizing-it-e85385fd354d">The React Design Pattern You’re Using Without Even Realizing It</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is a NodeList an Array? Even Senior Front-End Devs Fail This Interview Question]]></title>
            <link>https://blog.devgenius.io/is-a-nodelist-an-array-even-senior-front-end-devs-forget-this-interview-question-6a62d5bdba21?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a62d5bdba21</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 12:57:04 GMT</pubDate>
            <atom:updated>2024-08-19T19:46:21.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnRrHqHM5wqKM5xJsieFJw.jpeg" /></figure><p>When working with the <strong>DOM</strong> in <strong>JavaScript</strong> or <strong>TypeScript</strong>, you often encounter the <strong>NodeList</strong> object, usually returned by methods like <strong>document.querySelectorAll</strong>. At first glance, a <strong>NodeList</strong> might seem similar to an array, but there’s a critical distinction: <strong>NodeList is a collection,</strong> <strong>not a true array</strong>. This difference has important implications for how you work with it.</p><h4><strong>What is a NodeList?</strong></h4><p>A <strong>NodeList</strong> is a collection of <strong>DOM</strong> nodes, such as elements, text nodes, or comments. It can be either <strong>live</strong> or <strong>static</strong>:</p><ul><li><strong>Live NodeList:</strong> Automatically updates when the document changes. For example, <strong>document.getElementsByTagName</strong> returns a live <strong>NodeList</strong>.</li><li><strong>Static NodeList:</strong> Does not change when the document updates. <strong>document.querySelectorAll</strong> returns a static <strong>NodeList</strong>.</li></ul><h4><strong>Why is NodeList Not an Array?</strong></h4><p>Despite its array-like structure, a <strong>NodeList</strong> is not a true array. Here’s why:</p><p><strong>Inheritance and Prototype Chain:</strong></p><ul><li><strong>NodeList</strong> does not inherit from <strong>Array</strong>. It is an object with its own specific prototype chain.</li><li><strong>Arrays</strong> in JavaScript are instances of the Array constructor, which comes with built-in methods like map, filter, reduce, and forEach. Since <strong>NodeList</strong> is not an instance of Array, it does not have access to these methods by default.</li></ul><p><strong>Limited Methods:</strong></p><ul><li>While <strong>NodeList</strong> is iterable and can be accessed using an index (e.g., nodeList[0]), it does not include most of the array methods you might expect, such as map or reduce.</li><li>Some older browsers do not support <strong>forEach</strong> on <strong>NodeList</strong>, though modern environments do provide this method. However, even with forEach, other array methods remain unavailable.</li></ul><h4><strong>How to Work with NodeList as an Array in TypeScript</strong></h4><p>To use array methods on a <strong>NodeList</strong>, you must convert it to an actual array. In TypeScript, this is typically done using <strong>Array.from()</strong> or the spread operator (…).</p><p><strong>Example: Converting NodeList to an Array Using Array.from</strong></p><pre>const nodeList = document.querySelectorAll(&#39;.example-class&#39;);<br><br>// Convert NodeList to an array<br>const nodesArray: HTMLElement[] = Array.from(nodeList) as HTMLElement[];<br><br>// Now you can use array methods<br>nodesArray.forEach(node =&gt; {<br>  console.log(node.textContent);<br>});</pre><p><strong>Example: Converting NodeList to an Array Using the Spread Operator</strong></p><pre>const nodeList = document.querySelectorAll(&#39;.example-class&#39;);<br><br>// Convert NodeList to an array using the spread operator<br>const nodesArray: HTMLElement[] = [...nodeList] as HTMLElement[];<br><br>// Now you can use array methods<br>const textContents = nodesArray.map(node =&gt; node.textContent);<br>console.log(textContents);</pre><h4><strong>Why Convert to an Array?</strong></h4><p>By <strong>converting a NodeList to an array</strong>, you <strong>unlock the full power of array methods</strong>. This is <strong>especially useful in</strong> <strong>TypeScript</strong>, where the static typing can help you catch potential issues early.</p><p>For example, with an array, you can safely use:</p><ul><li>map to transform each node into something else (e.g., extracting text content).</li><li>filter to keep only the nodes that meet certain criteria.</li><li>reduce to aggregate information from the nodes.</li></ul><p>While a <strong>NodeList</strong> may look and act like an array in some respects, it’s fundamentally different. Being a <strong>collection of nodes</strong> rather than an actual array means <strong>you can’t directly use array methods like map or filter</strong>. By converting a <strong>NodeList</strong> to an array using <strong>Array.from</strong> or the spread operator, you can work with it just as you would with any other array in JavaScript or <strong>TypeScript</strong>.</p><p>This distinction is crucial for developers working with the <strong>DOM</strong>, especially in <strong>TypeScript</strong>, where understanding types and their methods is key to writing <strong>bug-free code</strong>.</p><p>Feel free to use this article as a reference or guide for understanding the <strong>differences between NodeList and arrays</strong>, and how to work with each in TypeScript!</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><p>Image by <a href="https://pixabay.com/users/vilkasss-35420724/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8764524">Vilius Kukanauskas</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8764524">Pixabay</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a62d5bdba21" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/is-a-nodelist-an-array-even-senior-front-end-devs-forget-this-interview-question-6a62d5bdba21">Is a NodeList an Array? Even Senior Front-End Devs Fail This Interview Question</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Guards in TypeScript and Their Role in React Development]]></title>
            <link>https://blog.devgenius.io/type-guards-in-typescript-and-their-role-in-react-development-a6ce2d811f54?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6ce2d811f54</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 13:54:28 GMT</pubDate>
            <atom:updated>2024-08-19T14:24:20.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwE-5N6zbX1OuEwbc2ZY6g.jpeg" /></figure><p>One of the powerful features of TypeScript is <strong>type guards</strong>, which play a crucial role in ensuring that your code behaves as expected. <strong>Type guards are particularly useful in the context of React development</strong>, where handling different types of props and state values is common.</p><p>In this article, we’ll explore <strong>what type guards are</strong>, why they are important in TypeScript, <strong>and</strong> <strong>how you can use them in React applications</strong>.</p><h3><strong>What Are Type Guards?</strong></h3><p><strong>Type guards</strong> are expressions that <strong>perform runtime checks</strong> to ensure that a variable or an object property is of a specific type. They <strong>allow TypeScript to refine the type of a variable within a certain scope</strong>, providing more precise type checking and enabling safer code.</p><p><strong>Type guards can be implemented in various ways, including:</strong></p><ul><li>Using <strong>typeof</strong></li><li>Using <strong>instanceof</strong></li><li>Using <strong>in</strong></li><li>Using custom type guard functions</li></ul><p>Let’s check each of these and see how they can be applied in a React context.</p><h4><strong>Type Guards with typeof</strong></h4><p>The typeof operator in JavaScript returns a string indicating the type of the operand. TypeScript can use this information to narrow down the type of a variable.</p><pre>interface NumberProps {<br>  value: number;<br>}<br><br>interface StringProps {<br>  value: string;<br>}<br><br>type Props = NumberProps | StringProps;<br><br>const DisplayValue: React.FC&lt;Props&gt; = ({ value }) =&gt; {<br>  if (typeof value === &#39;string&#39;) {<br>    return &lt;span&gt;{value.toUpperCase()}&lt;/span&gt;;<br>  }<br><br>  return &lt;span&gt;{value.toFixed(2)}&lt;/span&gt;;<br>};</pre><p>In the DisplayValue component, we accept a prop called value that can either be a string or a number. Using a typeof type guard, we check if value is a string and apply the appropriate transformation. If value is not a string, TypeScript automatically narrows it down to a number.</p><h4><strong>Type Guards with instanceof</strong></h4><p>The instanceof operator checks if an object is an instance of a particular class or constructor function. This is particularly useful when working with custom classes or more complex data structures.</p><pre>class User {<br>  constructor(public name: string) {}<br>}<br><br>class Admin extends User {<br>  constructor(name: string, public permissions: string[]) {<br>    super(name);<br>  }<br>}<br><br>type UserRole = User | Admin;<br><br>const UserProfile: React.FC&lt;{ user: UserRole }&gt; = ({ user }) =&gt; {<br>  if (user instanceof Admin) {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Admin: {user.name}&lt;/h1&gt;<br>        &lt;p&gt;Permissions: {user.permissions.join(&#39;, &#39;)}&lt;/p&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  return &lt;h1&gt;User: {user.name}&lt;/h1&gt;;<br>};</pre><p>In the UserProfile component, we use the instanceof operator to determine whether the user prop is an instance of the Admin class. If it is, we display the admin’s permissions; otherwise, we treat the user as a regular User.</p><h4>Type Guards with in</h4><p>The in operator is another type guard in TypeScript, which checks whether a property exists in an object. This is particularly useful when dealing with union types that have overlapping or optional properties.</p><pre>interface LoadingState {<br>  status: &#39;loading&#39;;<br>}<br><br>interface SuccessState {<br>  status: &#39;success&#39;;<br>  data: string[];<br>}<br><br>interface ErrorState {<br>  status: &#39;error&#39;;<br>  message: string;<br>}<br><br>type FetchState = LoadingState | SuccessState | ErrorState;<br><br>const FetchResult: React.FC&lt;{ state: FetchState }&gt; = ({ state }) =&gt; {<br>  if (&#39;data&#39; in state) {<br>    return (<br>      &lt;ul&gt;<br>        {state.data.map((item, index) =&gt; (<br>          &lt;li key={index}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    );<br>  }<br><br>  if (&#39;message&#39; in state) {<br>    return &lt;p&gt;Error: {state.message}&lt;/p&gt;;<br>  }<br><br>  return &lt;p&gt;Loading...&lt;/p&gt;;<br>};</pre><p>In the FetchResult component, we use the in operator to check whether the state object contains the data or message property. This allows us to handle each state correctly based on the presence of specific properties.</p><h4><strong>Custom Type Guards</strong></h4><p>Sometimes, you might need to create custom type guards, especially when working with more complex or abstract types. A custom type guard is simply a function that returns a boolean and uses a type predicate (param is Type) to inform TypeScript of the type narrowing.</p><pre>interface LoadingState {<br>  status: &#39;loading&#39;;<br>}<br><br>interface SuccessState {<br>  status: &#39;success&#39;;<br>  data: string[];<br>}<br><br>interface ErrorState {<br>  status: &#39;error&#39;;<br>  message: string;<br>}<br><br>type FetchState = LoadingState | SuccessState | ErrorState;<br><br>function isSuccessState(state: FetchState): state is SuccessState {<br>  return state.status === &#39;success&#39;;<br>}<br><br>const FetchResult: React.FC&lt;{ state: FetchState }&gt; = ({ state }) =&gt; {<br>  if (isSuccessState(state)) {<br>    return (<br>      &lt;ul&gt;<br>        {state.data.map((item, index) =&gt; (<br>          &lt;li key={index}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    );<br>  }<br><br>  if (state.status === &#39;loading&#39;) {<br>    return &lt;p&gt;Loading...&lt;/p&gt;;<br>  }<br><br>  return &lt;p&gt;Error: {state.message}&lt;/p&gt;;<br>};</pre><p>In the FetchResult component, we define a custom type guard isSuccessState to determine if the state is of type SuccessState. This allows us to safely access the data property when rendering the list of items.</p><h3><strong>Why Type Guards Are Useful in React</strong></h3><ol><li><strong>Enhanced Type Safety:</strong> Type guards help ensure that your React components only access properties that are valid for the given type, reducing the chances of runtime errors.</li><li><strong>Cleaner Code:</strong> By narrowing down types, type guards allow you to write more concise and readable code. They eliminate the need for extensive type casting, which can clutter your code and introduce errors.</li><li><strong>Better Developer Experience:</strong> Type guards improve the developer experience by enabling better autocompletion and intelligent code suggestions in your IDE. This makes your codebase easier to work with and reduces cognitive load.</li><li><strong>More Robust Components:</strong> When dealing with multiple types of props or state objects, type guards help create more robust components that can gracefully handle different scenarios, making your React applications more reliable.</li></ol><p><strong>Type guards are a powerful feature</strong> in TypeScript that can significantly improve the quality of your code, especially in complex React applications. <strong>By using typeof, instanceof, and custom type guards, you can ensure that your components handle different types safely and efficiently.</strong> This leads to more maintainable, less error-prone code and a better overall development experience.</p><p>Whether you’re building simple components or large-scale applications, understanding and <strong>utilizing type guards will help you write better</strong>, more reliable <strong>TypeScript</strong> code in <strong>React</strong>.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><p>Image by <a href="https://pixabay.com/users/janbaby-3005373/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2168234">Jan Alexander</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2168234">Pixabay</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6ce2d811f54" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/type-guards-in-typescript-and-their-role-in-react-development-a6ce2d811f54">Type Guards in TypeScript and Their Role in React Development</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The MiG-105: The Soviet Union’s Forgotten Spaceplane]]></title>
            <link>https://medium.com/@maciejpoppek/the-mig-105-the-soviet-unions-forgotten-spaceplane-c3384769bdba?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3384769bdba</guid>
            <category><![CDATA[history]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[nasa]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 15:20:52 GMT</pubDate>
            <atom:updated>2024-08-19T14:25:18.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8JpqmXwPIJ2urGsZO1hWg.png" /></figure><p>The Cold War era was marked by intense competition between the United States and the Soviet Union, with the <strong>space race</strong> serving as one of the most visible arenas for this geopolitical rivalry. While the <strong>American Apollo program</strong> culminated in a manned moon landing, the Soviet Union explored various ambitious projects that, if fully realized, might have significantly altered the trajectory of space exploration. Among these projects was the <strong>MiG-105,</strong> <strong>an experimental spaceplane</strong> designed to bolster Soviet capabilities in space. Though less well-known than other Soviet space endeavors, the <strong>MiG-105</strong> represents a fascinating chapter in aerospace history and offers insights into the USSR’s vision of space dominance.</p><h4><strong>Origins of the MiG-105</strong></h4><p>The <strong>MiG-105</strong>, also known as the <strong>“Lapot”</strong> (Russian for “shoe” or “bast shoe”) due to its unique shape, was part of a broader Soviet project called <strong>Spiral</strong>, initiated in the 1960s. <strong>The Spiral program was conceived as a response to the United States’ X-20 Dyna-Soar project</strong>, which aimed to create a manned spaceplane capable of both orbital flight and reconnaissance missions. <strong>Though the Dyna-Soar was eventually canceled, the Spiral program pressed on</strong>, reflecting the Soviet Union’s determination to maintain parity with — or surpass — American space technology.</p><p>The <strong>MiG-105</strong> was envisioned as the orbital stage of the Spiral system, which included three primary components: a hypersonic booster aircraft, the <strong>MiG-105</strong> spaceplane, and an expendable rocket stage for orbital insertion. <strong>The plan was to use the booster aircraft to carry the MiG-105 to high altitudes, where the spaceplane would detach, ignite its own engines, and enter orbit.</strong> After completing its mission, the <strong>MiG-105</strong> would glide back to Earth, landing on a conventional runway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfGizdP8rzoP6xDok51sPg.png" /></figure><h4><strong>Design and Development</strong></h4><p>Design work on the <strong>MiG-105</strong> began in earnest in the early 1960s under the leadership of <strong>Artem Mikoyan</strong>, a prominent Soviet aerospace engineer and co-founder of the Mikoyan design bureau, responsible for the development of the MiG series of fighter aircraft. <strong>The MiG-105 was designed with a lifting body configuration, which allowed it to generate lift during re-entry and landing without the need for large wings.</strong> This design was intended to provide greater maneuverability and survivability during re-entry compared to traditional capsule designs.</p><p><strong>The spaceplane featured a stubby, flat-bottomed fuselage with a nose that angled sharply downward. This configuration gave the MiG-105 its characteristic “shoe-like” appearance.</strong> The cockpit was positioned at the front of the fuselage, with small, delta-shaped wings mounted near the rear. The <strong>MiG-105</strong> was equipped with an advanced heat shield made of reinforced carbon-carbon composite, designed to protect the vehicle during the intense heat of re-entry.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzJy3f72fock%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzJy3f72fock&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzJy3f72fock%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d5021bba7ee80913d4e5e503ba826e/href">https://medium.com/media/89d5021bba7ee80913d4e5e503ba826e/href</a></iframe><h4><strong>Testing and Trials</strong></h4><p>The first flight of the <strong>MiG-105</strong> prototype occurred in <strong>1969</strong>, but this and subsequent tests were limited to suborbital missions. The initial test flights were conducted as unpowered glides, launched from a modified bomber aircraft. These tests focused on evaluating the vehicle’s aerodynamic properties and handling characteristics during approach and landing.</p><p>In <strong>1976</strong>, a modified version of the <strong>MiG-105</strong>, designated <strong>MiG-105.11</strong>, was flown in a series of atmospheric tests to further refine the design. The <strong>MiG-105.11</strong> was equipped with a rocket engine to simulate the conditions of re-entry and powered flight. These tests provided valuable data on the spaceplane’s performance, but they also revealed numerous technical challenges that needed to be addressed before the vehicle could be deemed spaceworthy.</p><h4><strong>The Spiral Program and Its Ambitious Goals</strong></h4><p><strong>The ultimate goal</strong> of the Spiral program <strong>was to create a reusable, manned spacecraft </strong>capable of performing a wide range of military and reconnaissance missions. The Soviet Union envisioned the <strong>MiG-105</strong> as a versatile platform that could be used for orbital reconnaissance, satellite interception, and even as a potential space-based bomber. In this sense, the <strong>MiG-105</strong> represented a <strong>bold attempt to militarize space and gain a strategic advantage over the United States.</strong></p><p>Had the Spiral program been fully realized, it could have significantly changed the course of the space race. The <strong>MiG-105</strong>’s ability to launch from a conventional runway, complete its mission in orbit, and return to Earth with precision would have provided the Soviet Union with unparalleled flexibility in space operations. <strong>Moreover, the reusable nature of the spaceplane would have offered significant cost savings</strong> <strong>compared to expendable launch systems, potentially allowing the Soviet Union to conduct more frequent and varied missions in space.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpP-5ZzsC2hZPVRO7FxFsA.png" /></figure><h4><strong>The Program’s Demise and Legacy</strong></h4><p>Despite its promise, the Spiral program, including the <strong>MiG-105</strong>, faced numerous technical and logistical challenges. <strong>The complexities of developing a fully reusable spaceplane were daunting</strong>, and the Soviet Union’s focus began to shift towards other space projects, such as the Salyut space stations and the Energia-Buran program. <strong>By the late 1970s, the Spiral program was effectively shelved</strong>, and the<strong> MiG-105</strong> never progressed beyond the experimental stage.</p><p>However, the <strong>MiG-105</strong> was not entirely forgotten. The data and experience gained from the <strong>MiG-105</strong>’s development contributed to the Soviet Union’s later efforts in reusable spacecraft, most notably the <strong>Buran</strong> space shuttle. The Buran program, which culminated in an unmanned orbital flight in 1988, was in many ways the spiritual successor to the <strong>MiG-105</strong> and reflected the same underlying ambition to create a reusable, multipurpose space vehicle.</p><p>The <strong>MiG-105</strong> stands as a testament to the Soviet Union’s determination to push the boundaries of aerospace technology during the height of the Cold War. <strong>While the project ultimately fell short of its lofty goals, it represents a fascinating “what if” in the history of the space race.</strong> Had the Spiral program succeeded, it might have altered the balance of power in space, giving the Soviet Union a significant advantage in military and reconnaissance operations. Instead, the <strong>MiG-105</strong> remains a symbol of unfulfilled potential and a reminder of the many challenges inherent in space exploration.</p><p>The story of the <strong>MiG-105</strong> highlights the complex interplay between technological ambition and geopolitical rivalry that characterized the space race. <strong>Although the Soviet Union was ultimately outpaced by the United States in many aspects of space exploration</strong>, projects like the <strong>MiG-105</strong> demonstrate that the race was far closer and more competitive than is often remembered.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3384769bdba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why DRY Principle in React is Crucial and Often Overlooked Especially by Junior Developers]]></title>
            <link>https://blog.devgenius.io/why-dry-principle-in-react-is-crucial-and-often-overlooked-especially-by-junior-developers-32acd5b750a2?source=rss-ac4582d6194a------2</link>
            <guid isPermaLink="false">https://medium.com/p/32acd5b750a2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maciej Poppek]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 17:00:09 GMT</pubDate>
            <atom:updated>2024-08-19T14:25:46.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDHLeO_zNFDFVDbpe1Lm7g.jpeg" /></figure><p>The <strong>DRY (Don’t Repeat Yourself)</strong> <strong>principle</strong> is a <strong>fundamental concept</strong> in software development <strong>that emphasizes the reduction of code duplication</strong>. <strong>The idea is simple: every piece of knowledge or logic in your code should have a single, unambiguous representation. </strong>When writing code, if you find yourself copying and pasting similar blocks of code across different parts of your application, it’s a sign that you might need to refactor your code to be more DRY-compliant.</p><p><strong>In React, particularly when using TypeScript, adhering to the DRY principle can significantly enhance the maintainability, readability, and scalability of your codebase.</strong> Despite its importance, many junior developers tend to overlook DRY, focusing more on getting things to work rather than writing clean, reusable code. This article will explore the <strong>importance of the DRY principle in React development</strong> and provide examples of how to apply it effectively.</p><h3><strong>Why DRY is Crucial in React Development</strong></h3><h4><strong>1. Code Maintainability</strong></h4><p>Imagine you have a React application with multiple forms, each handling user input in a slightly different way. You might be tempted to write separate event handlers for each form:</p><pre>const handleNameChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>  setName(e.target.value);<br>};<br><br>const handleEmailChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>  setEmail(e.target.value);<br>};<br><br>const handlePasswordChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>  setPassword(e.target.value);<br>};</pre><p><strong>Each of these functions is almost identical, differing only in the state they update.</strong> If you need to change how you handle input events, you’d have to update each of these functions individually, increasing the risk of introducing bugs. Instead, you could refactor this logic into a single, reusable function:</p><pre>const handleInputChange = (setter: React.Dispatch&lt;React.SetStateAction&lt;string&gt;&gt;) =&gt; <br>  (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    setter(e.target.value);<br>};<br><br>const handleNameChange = handleInputChange(setName);<br>const handleEmailChange = handleInputChange(setEmail);<br>const handlePasswordChange = handleInputChange(setPassword);</pre><p>By applying the DRY principle, you’ve reduced redundancy, making the code easier to maintain and less prone to errors.</p><h4><strong>2. Reducing Bugs and Errors</strong></h4><p>Consider a scenario where you have multiple components that display user information. Without DRY, you might write similar code in each component to format and display this information:</p><pre>// UserCard.tsx<br>const UserCard = ({ user }: { user: User }) =&gt; (<br>  &lt;div&gt;<br>    &lt;p&gt;{user.firstName} {user.lastName}&lt;/p&gt;<br>    &lt;p&gt;{user.email}&lt;/p&gt;<br>  &lt;/div&gt;<br>);<br><br>// UserProfile.tsx<br>const UserProfile = ({ user }: { user: User }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h1&gt;{user.firstName} {user.lastName}&lt;/h1&gt;<br>    &lt;p&gt;{user.email}&lt;/p&gt;<br>  &lt;/div&gt;<br>);</pre><p>If you later need to change how the user’s name is formatted, you’ll have to update every component that displays this information. Instead, you could extract the formatting logic into a reusable component:</p><pre>const UserName = ({ user }: { user: User }) =&gt; (<br>  &lt;span&gt;{user.firstName} {user.lastName}&lt;/span&gt;<br>);<br><br>// In UserCard.tsx and UserProfile.tsx<br>&lt;UserName user={user} /&gt;</pre><p>This approach reduces the likelihood of errors because any change to the formatting logic only needs to be made in one place.</p><h4><strong>3. Enhanced Readability</strong></h4><p>DRY code is often more readable. Instead of scattering similar logic throughout your application, you can centralize it in reusable functions or components. Consider a React component that displays different types of notifications:</p><pre>const SuccessNotification = ({ message }: { message: string }) =&gt; (<br>  &lt;div className=&quot;success&quot;&gt;{message}&lt;/div&gt;<br>);<br><br>const ErrorNotification = ({ message }: { message: string }) =&gt; (<br>  &lt;div className=&quot;error&quot;&gt;{message}&lt;/div&gt;<br>);</pre><p>While this works, it’s repetitive. You can improve readability by creating a single Notification component:</p><pre>const Notification = ({ type, message }: { type: &#39;success&#39; | &#39;error&#39;, message: string }) =&gt; (<br>  &lt;div className={type}&gt;{message}&lt;/div&gt;<br>);<br><br>// Usage<br>&lt;Notification type=&quot;success&quot; message=&quot;Operation completed successfully!&quot; /&gt;<br>&lt;Notification type=&quot;error&quot; message=&quot;An error occurred.&quot; /&gt;</pre><p>This not only makes the code more concise but also makes it easier to understand and maintain.</p><h4><strong>4. Optimized Performance</strong></h4><p>Repetitive code can lead to unnecessary re-renders in React, which impacts performance. Suppose you have two components that fetch data from an API and display it. Without DRY, you might write separate fetch logic in each component:</p><pre>// ComponentA.tsx<br>useEffect(() =&gt; {<br>  fetch(&#39;/api/dataA&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; setDataA(data));<br>}, []);<br><br>// ComponentB.tsx<br>useEffect(() =&gt; {<br>  fetch(&#39;/api/dataB&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; setDataB(data));<br>}, []);</pre><p>This leads to duplicated logic and potentially more network requests than necessary. Instead, you can create a custom hook to handle data fetching:</p><pre>const useFetchData = (url: string) =&gt; {<br>  const [data, setData] = useState&lt;any&gt;(null);<br><br>  useEffect(() =&gt; {<br>    fetch(url)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; setData(data));<br>  }, [url]);<br><br>  return data;<br>};<br><br>// In ComponentA.tsx and ComponentB.tsx<br>const dataA = useFetchData(&#39;/api/dataA&#39;);<br>const dataB = useFetchData(&#39;/api/dataB&#39;);</pre><p>This DRY approach not only reduces repetition but also makes it easier to manage API requests efficiently.</p><h4><strong>5. TypeScript and DRY: A Perfect Match</strong></h4><p>TypeScript’s strong typing system can be a powerful ally in adhering to the DRY principle. For example, consider a scenario where multiple components share a common prop structure:</p><pre>interface ButtonProps {<br>  label: string;<br>  onClick: () =&gt; void;<br>}<br><br>const PrimaryButton = ({ label, onClick }: ButtonProps) =&gt; (<br>  &lt;button className=&quot;primary&quot; onClick={onClick}&gt;{label}&lt;/button&gt;<br>);<br><br>const SecondaryButton = ({ label, onClick }: ButtonProps) =&gt; (<br>  &lt;button className=&quot;secondary&quot; onClick={onClick}&gt;{label}&lt;/button&gt;<br>);</pre><p>Here, ButtonProps is defined once and reused across multiple components, ensuring consistency and reducing duplication. If you need to update the prop structure, you can do so in one place, and TypeScript will enforce the changes across all components that use ButtonProps.</p><h3><strong>Why Junior Developers Often Overlook DRY</strong></h3><h4><strong>1. Lack of Experience with Codebase Growth</strong></h4><p><strong>Junior developers may not yet appreciate the long-term consequences of code duplication.</strong> Early in their careers, they might prioritize getting features to work without fully considering the impact of repetitive code on future maintainability and scalability. <strong>They might not have experienced the pain of maintaining a large, repetitive codebase, so they might underestimate the importance of the DRY principle.</strong></p><h4><strong>2. Misunderstanding of Component Reusability</strong></h4><p><strong>React’s component-based architecture encourages reuse</strong>, but junior developers might struggle with how to properly abstract and reuse components. <strong>It’s easy to fall into the trap of duplicating similar components instead of refactoring them into more generic, reusable ones.</strong></p><p>For instance, creating multiple components with minor differences rather than leveraging props or higher-order components (HOCs) is a common mistake. They might create UserProfile, UserCard, and UserDetails components with similar code rather than refactoring them to share a common UserInfo component.</p><h4><strong>3. Focus on Immediate Solutions</strong></h4><p>Under pressure to deliver features quickly, junior developers might prioritize immediate solutions over long-term best practices. <strong>This can lead to “quick and dirty” coding that duplicates logic to achieve functionality, rather than taking the time to refactor code in a DRY-compliant manner.</strong></p><h4><strong>4. Overcomplication of Abstraction</strong></h4><p>Ironically, in their efforts to avoid repetition, some junior developers might over-abstract their code, leading to a different set of problems. <strong>The key to DRY is not just about avoiding repetition but doing so in a way that doesn’t make the code unnecessarily complex.</strong> Striking the right balance between abstraction and clarity is a skill that develops with experience.</p><h3><strong>Strategies for Adopting DRY in React</strong></h3><h4><strong>1. Identify Common Patterns Early</strong></h4><p><strong>As you develop, pay attention to repeating patterns</strong> in your components or logic. When you notice duplication, consider whether you can refactor it into a reusable component or function. <strong>Tools like React’s useCallback and useMemo hooks can also help in optimizing and reusing logic.</strong></p><p>For example, if you notice multiple components handling similar input logic, consider creating a custom hook:</p><pre>const useInput = (initialValue: string) =&gt; {<br>  const [value, setValue] = useState(initialValue);<br><br>  const onChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    setValue(e.target.value);<br>  };<br><br>  return { value, onChange };<br>};<br><br>// Usage in components<br>const nameInput = useInput(&#39;&#39;);<br>const emailInput = useInput(&#39;&#39;);</pre><h4><strong>2. Leverage TypeScript’s Strengths</strong></h4><p>Use TypeScript’s interfaces and types to create reusable data structures. For instance, if you find yourself <strong>defining similar</strong> <strong>prop types in multiple components</strong>, consider creating a shared type or interface that can be reused across these components.</p><p>For example, if multiple components are dealing with user data:</p><pre>interface User {<br>  firstName: string;<br>  lastName: string;<br>  email: string;<br>}<br><br>const UserProfile = ({ user }: { user: User }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h1&gt;{user.firstName} {user.lastName}&lt;/h1&gt;<br>    &lt;p&gt;{user.email}&lt;/p&gt;<br>  &lt;/div&gt;<br>);</pre><p>By defining a User interface, you ensure that all components using user data stay consistent and reduce code duplication.</p><h4><strong>3. Modularize Your Code</strong></h4><p><strong>Break down large components or functions into smaller, reusable modules. </strong>This not only adheres to the DRY principle but also aligns with the single responsibility principle (SRP), making your codebase more modular and easier to test.</p><p>For example, if you have a large form component, consider breaking it down into smaller subcomponents:</p><pre>const NameField = ({ name, onNameChange }: { name: string, onNameChange: (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; void }) =&gt; (<br>  &lt;input value={name} onChange={onNameChange} /&gt;<br>);<br><br>const EmailField = ({ email, onEmailChange }: { email: string, onEmailChange: (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; void }) =&gt; (<br>  &lt;input value={email} onChange={onEmailChange} /&gt;<br>);<br><br>// Usage in a form component<br>&lt;NameField name={name} onNameChange={handleNameChange} /&gt;<br>&lt;EmailField email={email} onEmailChange={handleEmailChange} /&gt;</pre><p>This approach makes each part of your form easier to manage and reuse in other forms.</p><h4><strong>4. Code Reviews and Pair Programming</strong></h4><p>Engage in code reviews and pair programming to catch instances of code duplication. <strong>Senior developers can provide valuable insights into how to refactor and avoid repetition. Code reviews are an excellent opportunity</strong> to reinforce the importance of the DRY principle and to share best practices.</p><h4><strong>5. Continuous Refactoring</strong></h4><p><strong>Refactoring should be a continuous process, not a one-time event.</strong> As your application evolves, new opportunities to apply the DRY principle will arise. Regularly revisit your codebase to identify areas where duplication can be reduced.</p><h3><strong>DRY is Key to Long-Term Success</strong></h3><p>The DRY principle is a cornerstone of effective software development, particularly in the context of React with TypeScript. By reducing code duplication, developers can create more maintainable, scalable, and bug-resistant applications. <strong>While junior developers may sometimes overlook DRY in their eagerness to deliver working features, understanding and applying this principle early in their careers will pay dividends as they grow as developers.</strong></p><p>By embracing <strong>DRY</strong> and leveraging the power of <strong>React</strong> and <strong>TypeScript</strong>, developers can build efficient applications that stand the test of time.</p><p>If you enjoyed my article, don’t forget to leave a few <strong>claps</strong> 👏🏻 and <strong>follow</strong> me to stay updated with the articles I publish 🙂</p><p>Image by <a href="https://pixabay.com/users/vilkasss-35420724/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8764526">Vilius Kukanauskas</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=8764526">Pixabay</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32acd5b750a2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/why-dry-principle-in-react-is-crucial-and-often-overlooked-especially-by-junior-developers-32acd5b750a2">Why DRY Principle in React is Crucial and Often Overlooked Especially by Junior Developers</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>