<?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 Sathya Reddy on Medium]]></title>
        <description><![CDATA[Stories by Sathya Reddy on Medium]]></description>
        <link>https://medium.com/@ksathyareddy7?source=rss-7eb7ef913f15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SCgeL5VHp_5QujWgJL4cew.jpeg</url>
            <title>Stories by Sathya Reddy on Medium</title>
            <link>https://medium.com/@ksathyareddy7?source=rss-7eb7ef913f15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:05:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ksathyareddy7/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[Understanding the Evolution of HTTP: From 1.1 to HTTP/3]]></title>
            <link>https://medium.com/@ksathyareddy7/understanding-the-evolution-of-http-from-1-1-to-http-3-2f00e490d4f1?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f00e490d4f1</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 04:53:20 GMT</pubDate>
            <atom:updated>2025-04-12T04:53:20.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYwwabpZNprhbnQHNkL4cw.png" /></figure><p>The jump from <strong>HTTP/1.1</strong> to <strong>HTTP/2 </strong>brought some major improvements in how data is transferred between the client (browser) and server.</p><h3>1. Request/Response Multiplexing</h3><p><strong>HTTP/1.1:</strong> Only <strong>one request per TCP connection</strong> at a time. Multiple requests cause what’s called “head-of-line blocking” unless the browser opens multiple TCP connections.</p><p><strong>HTTP/2:</strong> <strong>Multiple requests and responses</strong> can be sent in parallel <strong>over a single connection</strong>, thanks to <em>multiplexing</em>. This greatly reduces latency.</p><p><strong>Impact</strong>: No more blocking! Faster page loads, especially for sites with lots of assets (images, scripts, etc.).</p><h3>2. Binary Protocol vs Text-Based</h3><p><strong>HTTP/1.1:</strong> Text-based protocol. Easy to read, but slower for machines to parse.</p><p><strong>HTTP/2:</strong> Binary protocol. More efficient, less error-prone, and easier for computers to parse.</p><p><strong>Impact</strong>: Binary is faster to process than plain text, so things move quicker under the hood.</p><h3>3. Header Compression</h3><p><strong>HTTP/1.1:</strong> HTTP headers are sent as plain text with every request, often repeating the same info (e.g., cookies, user agents).</p><p><strong>HTTP/2:</strong> Uses <strong>HPACK</strong> header compression to minimize overhead.</p><p><strong>Impact</strong>: Reduces size of requests and responses, improving performance.</p><h3>4. Stream Prioritization</h3><p><strong>HTTP/1.1: </strong>No support for prioritization.</p><p><strong>HTTP/2:</strong> Allows clients to <strong>prioritize</strong> resources (like scripts or styles) so the most important ones are delivered first.</p><p><strong>Impact</strong>: Critical resources can be prioritized over less important ones (e.g., a logo vs. the main CSS).</p><h3>5. Single Connection</h3><p><strong>HTTP/1.1:</strong> Often needs <strong>6+ connections per domain</strong> to load everything efficiently.</p><p><strong>HTTP/2:</strong> All assets can be loaded over <strong>one persistent connection</strong>, reducing overhead and improving congestion control.</p><p><strong>Impact</strong>: This pairs very well with HTTPS since setting up fewer connections saves time during TLS handshakes.</p><h3>6. Server Push</h3><p><strong>HTTP/1.1:</strong> No support for server push.</p><p><strong>HTTP/2:</strong> Servers can <strong>“push” resources</strong> (like CSS or JS files) to the browser <strong>before it’s asked for them</strong>.</p><p><strong>Impact</strong>: Server can optimistically push future required resources. Think of it like the server saying, “You’ll need this soon, here you go.”</p><h3>🚀 HTTP3</h3><p>HTTP/3 is built on a new transport protocol called <strong>QUIC (Quick UDP Internet Connections)</strong> instead of TCP. QUIC was developed by Google and is designed to be faster, more secure, and more reliable, especially in modern network conditions like mobile and Wi-Fi connections.</p><h3>1. Uses QUIC Instead of TCP</h3><p>Unlike HTTP/1.1 and HTTP/2 (which use TCP), HTTP/3 runs over <strong>UDP</strong> using QUIC. This eliminates the need for slow TCP handshakes and allows faster connection setups.</p><h3><strong>2. Built-in TLS (TLS 1.3)</strong></h3><p>QUIC has encryption baked in — <strong>TLS is integrated directly into the protocol</strong>, reducing handshake steps and improving security and speed.</p><h3><strong>3.No Head-of-Line (HoL)</strong></h3><p>With TCP, if one packet is lost, everything waits until it’s retransmitted. QUIC fixes this by allowing <strong>independent streams</strong>, so packet loss doesn’t block others.</p><h3><strong>4. Better Performance on Mobile</strong></h3><p>QUIC is designed to handle network changes gracefully (like switching from Wi-Fi to 4G), making it more robust for mobile users.</p><p>🧑‍💻 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/ksathyareddy7/">ksathyareddy7</a> | <strong>Website</strong>: <a href="https://www.sathyareddy.dev/">ksathyareddy7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f00e490d4f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Does “Cascading” Mean in CSS? (With Specificity Explained)]]></title>
            <link>https://medium.com/@ksathyareddy7/what-does-cascading-mean-in-css-with-specificity-explained-cd999c8b5de4?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd999c8b5de4</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 18:05:46 GMT</pubDate>
            <atom:updated>2025-04-07T18:05:46.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9faUDhhObUK2B9O9Zetlg.png" /></figure><p>If you’ve worked with CSS for more than a few hours, you’ve likely run into this mysterious and slightly intimidating behavior where some styles seem to “win” over others. You write a rule, but it doesn’t apply. You override it… But that doesn’t work either. The answer often lies in the <strong>“C”</strong> of <strong>CSS</strong> — the <strong>Cascade</strong>.</p><p>Let’s unpack what cascading actually means and how <strong>specificity</strong> plays a crucial role in determining which styles are applied.</p><h3>🎯 What Is the Cascade?</h3><p>The <strong>Cascade</strong> is the algorithm CSS uses to resolve conflicts when multiple rules target the same element. CSS stands for <strong>Cascading Style Sheets</strong>, and the term “cascading” describes <strong>how the browser determines which styles to apply when multiple rules could match the same element</strong>.</p><h4>The Cascade Considers Three Main Factors:</h4><ol><li><strong>Origin and Importance</strong></li><li><strong>Specificity</strong></li><li><strong>Source Order</strong></li></ol><p>Let’s walk through each, and then dive deep into <strong>specificity</strong> with examples.</p><h3>1. 🧩 Origin and Importance</h3><p>There are different sources of styles:</p><ul><li><strong>Author stylesheets</strong> (your CSS files)</li><li><strong>User stylesheets</strong> (styles set by the user, e.g., in the browser)</li><li><strong>Browser stylesheets</strong> (default styles)</li></ul><p>Each of these can include normal styles or !important styles.</p><p><strong>Cascade Order of Importance</strong> (highest to lowest):</p><pre>1. User `!important`<br>2. Author `!important`<br>3. Author normal<br>4. User normal<br>5. Browser default</pre><p>So if you write a rule with !important, it overrides other normal rules—but !important should be used sparingly.</p><h3>2. 🧮 Specificity: Who Wins When Selectors Compete?</h3><p>Now let’s get to the real game-changer — <strong>specificity</strong>.</p><p>When multiple rules from the same origin apply to an element, <strong>specificity</strong> determines which one wins.</p><h3>🔢 Specificity is Calculated Like a Score:</h3><p>Each selector gets a score in the format:<br> <strong>(a, b, c, d)</strong></p><p>Where:</p><ul><li>a = inline styles (like style=&quot;&quot; in HTML)</li><li>b = number of ID selectors</li><li>c = number of class selectors, attribute selectors, and pseudo-classes</li><li>d = number of type selectors (like div, h1) and pseudo-elements</li></ul><p><strong>The higher the number from left to right, the more specific the rule.</strong></p><h3>📌 Specificity Examples</h3><p>Let’s explore this with actual CSS:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;style&gt;<br>    div p { color: green; }               /* (0,0,0,2) */<br>    .text p { color: blue; }              /* (0,0,1,1) */<br>    #main p { color: red; }               /* (0,1,0,1) */<br>    p { color: orange !important; }       /* (0,0,0,1) + !important */<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;main&quot; class=&quot;text&quot;&gt;<br>    &lt;p&gt;Hello World&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>🧠 Which Rule Applies?</h3><p>Let’s walk through this:</p><ol><li><strong>div p</strong> – Specificity: (0,0,0,2)</li><li><strong>.text p</strong> – Specificity: (0,0,1,1) → More specific than above</li><li><strong>#main p</strong> – Specificity: (0,1,0,1) → Even more specific</li><li><strong>p { color: orange !important; }</strong> – Specificity: (0,0,0,1)<br> But it has !important, so it takes precedence over others.</li></ol><p>Final color applied:<strong> <em>ORANGE</em></strong></p><p>If we remove !important, the color becomes <strong>RED</strong>, due to the higher specificity of the #main p rule.</p><h3>3. Source Order (Last One Wins)</h3><p>When two selectors have the <strong>same specificity</strong>, the one that comes <strong>later in the CSS file</strong> takes precedence.</p><pre>p {<br>  color: green;<br>}<br><br>p {<br>  color: blue;<br>}</pre><p>Even though both have the same specificity, the second one will apply (blue).</p><p><strong>💥 Inline Styles Override Almost Everything</strong></p><p>Inline styles (written directly in HTML) have the highest specificity (except for !important):</p><pre>&lt;p style=&quot;color: purple;&quot;&gt;Hello&lt;/p&gt; &lt;!-- (1,0,0,0) --&gt;</pre><p>This will override all previous CSS rules unless another rule uses !important.</p><h3>✅ Best Practices</h3><ul><li><strong>Avoid overusing </strong><strong>!important</strong>. It makes debugging a nightmare.</li><li><strong>Use class selectors for flexibility</strong> and avoid tying styles to IDs unless necessary.</li><li><strong>Keep specificity low</strong> and predictable.</li><li><strong>Understand the cascade</strong> to write cleaner, more maintainable CSS.</li></ul><h3>🧪 Bonus: Visual Specificity Calculator</h3><p>If you want to experiment with specificity, check out tools like:</p><ul><li><a href="https://specificity.keegan.st/">Specificity Calculator by keegan</a></li><li><a href="https://cssbootcamp.com/css/specificity-calculator">Specificity Calculator by CSSBootcamp</a></li></ul><h3>🧩 TL;DR</h3><ul><li><strong>Cascade</strong> resolves conflicts when multiple CSS rules apply.</li><li>CSS chooses based on:<br><strong>Origin &amp; Importance<br>Specificity<br>Source Order</strong></li><li><strong>Specificity is like a score</strong>. The higher, the stronger.</li><li>Inline styles and !important are the strongest, but use them carefully.</li></ul><p>If you want to connect with me, here are my socials.</p><p>🧑‍💻 <strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/ksathyareddy7/">ksathyareddy7</a> | <strong>Website</strong>: <a href="https://www.sathyareddy.dev/">ksathyareddy7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd999c8b5de4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Toast Notification System in React: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@ksathyareddy7/creating-a-toast-notification-system-in-react-a-step-by-step-guide-9b76b182d336?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b76b182d336</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 18:18:54 GMT</pubDate>
            <atom:updated>2025-04-05T11:34:05.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*7WW8JjtK35cvIItgxu8__g.png" /><figcaption>Toasts appearing at the right bottom of the application as user notifications</figcaption></figure><p>Notifications are a crucial part of most modern web applications, providing users with feedback about their actions, system updates, or errors they encounter. A simple way to notify the user is by using <strong>toast notifications</strong>, which are brief messages that appear on the screen for a short period.</p><p>This can be an interview question as well, where the interviewer will ask you to build a Toast Notification System. The question will be framed something like this:</p><p><strong>𝗛𝗼𝘄 𝘄𝗼𝘂𝗹𝗱 𝘆𝗼𝘂 𝗶𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁 𝗮 𝘁𝗼𝗮𝘀𝘁 𝗻𝗼𝘁𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻 𝘀𝘆𝘀𝘁𝗲𝗺 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁?</strong></p><ul><li>Describe how to handle global notification state and display logic.</li><li>How would you queue multiple notifications, set timeouts, and avoid overlapping?</li><li>Would you use Context, Redux, or a custom event system?</li></ul><p><a href="https://github.com/ksathyareddy7/frontend-mastery/tree/main/react-machine-coding/src/problems/ToastNotification"><strong>Link to Code Repository</strong></a></p><h3>What is a Toast Notification?</h3><p>A toast notification is a small pop-up message that is displayed on the screen for a short time. These notifications are often used to provide feedback to the user, like <strong>success</strong>, <strong>error</strong>, or <strong>informational</strong> messages, without interrupting their workflow. Once the message is shown, it disappears automatically after a short duration, or the user can dismiss it manually.</p><h3>Building the Toast Notification System</h3><p>We are going to use React Context as it is easy to setup and comes built in with React, which is more than enough to build our notification system.</p><h4><strong>1. Setting Up the Context for Notifications</strong></h4><p>To manage toast notifications globally in the app, we will use the <strong>Context API</strong>. The Context API helps us share the notification state across the entire app without having to pass props manually.</p><pre>// This file name: ToastNotificationContext<br><br>import React, {<br>  createContext,<br>  useState,<br>  ReactNode,<br>  useContext,<br>  useEffect,<br>} from &quot;react&quot;;<br><br>export enum NotificationTypes {<br>  success = &quot;success&quot;,<br>  error = &quot;error&quot;,<br>  info = &quot;info&quot;,<br>}<br><br>// notification object<br>export interface Notification {<br>  id: string;<br>  message: string;<br>  type: NotificationTypes;<br>  duration?: number; // milliseconds to show<br>}<br><br>interface NotificationContextProps {<br>  notificationsList: Notification[];<br>  addNotification: (notification: Notification) =&gt; void;<br>  removeNotification: (id: string) =&gt; void;<br>  CustomComponent?: React.ElementType;<br>}<br><br>const NotificationContext = createContext&lt;NotificationContextProps | undefined&gt;(<br>  undefined<br>);<br><br>export const useNotification = (): NotificationContextProps =&gt; {<br>  const context = useContext(NotificationContext);<br>  if (!context) {<br>    throw new Error(<br>      &quot;useNotification must be used within a NotificationProvider&quot;<br>    );<br>  }<br>  return context;<br>};</pre><p>Here, we define a Notification interface that holds the id, message, type, and an optional duration. The NotificationTypes enum helps categorize the notification type into success, error, or info.</p><p>We create a context NotificationContext to hold the notifications state, as well as two functions: addNotification to add a new notification and removeNotification to remove a notification.</p><h4>2. <strong>Creating the Notification Provider</strong></h4><p>The code below is part of the above file. I have split it into a separate chunk for better readability and understanding.</p><pre>// This file name: ToastNotificationContext<br><br>interface ToastNotificationProviderProps {<br>  children: ReactNode;<br>  customComponent?: React.ElementType;<br>}<br><br>export const ToastNotificationProvider = ({<br>  children,<br>  customComponent: CustomComponent,<br>}: ToastNotificationProviderProps) =&gt; {<br>  const [notificationsList, setNotificationsList] = useState&lt;Notification[]&gt;(<br>    []<br>  );<br><br>  const addNotification = (notification: Notification) =&gt; {<br>    setNotificationsList((prevNotifications) =&gt; [<br>      ...prevNotifications,<br>      notification,<br>    ]);<br>  };<br><br>  const removeNotification = (id: string) =&gt; {<br>    setNotificationsList((prevNotifications) =&gt;<br>      prevNotifications.filter((notification) =&gt; notification.id !== id)<br>    );<br>  };<br><br>  // remove notifications after a timeout<br>  useEffect(() =&gt; {<br>    notificationsList.forEach((notification) =&gt; {<br>      if (notification.duration) {<br>        const timeoutId = setTimeout(() =&gt; {<br>          removeNotification(notification.id);<br>        }, notification.duration);<br><br>        return () =&gt; clearTimeout(timeoutId);<br>      }<br>    });<br>  }, [notificationsList]);<br><br>  return (<br>    &lt;NotificationContext.Provider<br>      value={{<br>        notificationsList,<br>        addNotification,<br>        removeNotification,<br>        CustomComponent,<br>      }}<br>    &gt;<br>      {children}<br>    &lt;/NotificationContext.Provider&gt;<br>  );<br>};</pre><p>This ToastNotificationProvider contains the notificationsList state, which keeps track of all active notifications. When a new notification is added or removed, the state is updated. We use the useEffect hook to automatically remove notifications after the specified time duration using the setTimeout function. Whenever the component re-renders, we clear out all the timeouts to prevent memory leaks.</p><p>The ToastNotificationProvider also accepts an optional prop named customComponent that allows us to use a custom component to show toasts if we don’t want to use the default component.</p><h4>3. <strong>Displaying the Notifications</strong></h4><pre>// This file name: ToastContainer<br><br>import React from &quot;react&quot;;<br>import { useNotification } from &quot;./ToastNotificationContext&quot;;<br><br>// container that renders the list of notification this needs to be included at the top of the application<br>// inside notification provider along side the app component<br>export const ToastContainer = () =&gt; {<br>  const { notificationsList, removeNotification, CustomComponent } =<br>    useNotification();<br><br>  return (<br>    &lt;div className=&quot;toast-container&quot;&gt;<br>      {notificationsList.map((notification) =&gt; {<br>        if (CustomComponent) {<br>          return &lt;CustomComponent key={notification.id} {...notification} /&gt;;<br>        }<br><br>        return (<br>          &lt;div<br>            key={notification.id}<br>            className={`toast ${notification.type}`}<br>            style={{ marginTop: &quot;10px&quot; }}<br>          &gt;<br>            &lt;p&gt;{notification.message}&lt;/p&gt;<br>            &lt;button onClick={() =&gt; removeNotification(notification.id)}&gt;<br>              Close<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        );<br>      })}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>The ToastContainer component listens to the notifications in the context and maps through them to render each notification as CustomComponent if provided which gets all the details of the notification passed down as props, or uses the default component. Each default notification component has a Close button to manually dismiss it. The typenotification success, error, info can be used to style it differently.</p><h4>4. <strong>Triggering Notifications</strong></h4><pre>// This file name: ToastNotificationDemo<br><br>import React from &quot;react&quot;;<br>import { useNotification, NotificationTypes } from &quot;./ToastNotificationContext&quot;;<br><br>// The demo component with buttons to show notifications<br>export const ToastNotificationDemo = () =&gt; {<br>  const { addNotification } = useNotification();<br><br><br>  const showNotification = (type: NotificationTypes) =&gt; {<br>    const newNotification = {<br>      id: `${Date.now()}-${Math.floor(Math.random() * 1000)}`,<br>      message: `This is a ${type.toUpperCase()} toast notification`,<br>      type,<br>      duration: 3000,<br>    };<br>    addNotification(newNotification);<br>  };<br><br>  return (<br>    &lt;div className=&quot;buttons-container&quot;&gt;<br>      &lt;button onClick={() =&gt; showNotification(NotificationTypes.success)}&gt;<br>        Success Notification<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; showNotification(NotificationTypes.error)}&gt;<br>        Error Notification<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; showNotification(NotificationTypes.info)}&gt;<br>        Info Notification<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>To allow users to trigger notifications, we can create a simple demo component with buttons to show different types of notifications. <br>The ToastNotificationDemo has three buttons, each triggering a different type of notification (success, error, info) when clicked.</p><h4>5. Custom Toast Component</h4><p>I have built a small custom component to be used for the demo purpose, you can skip this as this is optional.</p><pre>import React from &quot;react&quot;;<br>import { Notification } from &quot;./ToastNotificationContext&quot;;<br><br>export const CustomToast = ({ message, type }: Notification) =&gt; {<br>  return (<br>    &lt;div className={`custom-toast custom-${type}`}&gt;<br>      &lt;p&gt;{message}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>6. <strong>Putting It All Together</strong></h4><pre>// This file name: ToastNotificationAppContainer<br><br>import React from &quot;react&quot;;<br>import { ToastNotificationProvider } from &quot;./ToastNotificationContext&quot;;<br>import { ToastContainer } from &quot;./ToastContainer&quot;;<br>import { ToastNotificationDemo } from &quot;./ToastNotificationDemo&quot;;<br>import &quot;./ToastNotification.styles.css&quot;;<br>import { CustomToast } from &quot;./CustomToast&quot;;<br><br>export const ToastNotificationAppContainer = () =&gt; {<br>  return (<br>    &lt;ToastNotificationProvider customComponent={CustomToast}&gt;<br>      &lt;ToastContainer /&gt;<br>      &lt;ToastNotificationDemo /&gt;<br>    &lt;/ToastNotificationProvider&gt;<br>  );<br>};</pre><pre>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;ToastNotificationAppContainer /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>In the main component ToastNotificationAppContainer we wrap the app with the ToastNotificationProvider so that the notification state is accessible throughout the app, the customComponent prop is optional you can skip passing this if you skipped the above step. The ToastContainer is included to render the notifications, and ToastNotificationDemo allows the user to trigger different types of notifications.</p><h4>6. <strong>Styling the Notifications</strong></h4><p>To make the notifications look nice, you can add some basic CSS styles.</p><pre>/* This file name: ToastNotification.styles.css */<br>/* buttons to trigger various types of notification */<br><br>.buttons-container {<br>  display: flex;<br>  padding: 20px;<br>}<br><br>.buttons-container button {<br>  padding: 10px;<br>  border-radius: 4px;<br>  font-weight: 500;<br>  font-size: 18px;<br>  margin-right: 40px;<br>  background-color: transparent;<br>  cursor: pointer;<br>}<br><br>.button-success {<br>  border-color: #4caf50;<br>  color: #4caf50;<br>}<br><br>.button-error {<br>  border-color: #f44336;<br>  color: #f44336;<br>}<br><br>.button-info {<br>  border-color: #eea506;<br>  color: #eea506;<br>}<br><br>/* toast container to display stack of notification */<br><br>.toast-container {<br>  position: fixed;<br>  bottom: 20px;<br>  right: 20px;<br>  z-index: 1000;<br>}<br><br>.toast {<br>  background-color: #4caf50;<br>  color: white;<br>  padding: 10px 20px;<br>  border-radius: 5px;<br>  margin-top: 10px;<br>  transition: opacity 0.3s ease;<br>}<br><br>.toast.error {<br>  background-color: #f44336;<br>}<br><br>.toast.success {<br>  background-color: #4caf50;<br>}<br><br>.toast.info {<br>  background-color: #eea506;<br>}<br><br>.toast button {<br>  margin-left: 10px;<br>  background: transparent;<br>  color: white;<br>  border: none;<br>  cursor: pointer;<br>}<br><br>/* custom toast component */<br><br>.custom-toast {<br>  padding: 16px;<br>  border: 1px solid white;<br>  border-radius: 4px;<br>  background-color: transparent;<br>  margin-bottom: 10px;<br>}<br><br>.custom-toast p {<br>  margin: 0;<br>  padding: 0;<br>}<br><br>.custom-success {<br>  background-color: rgba(76, 175, 80, 0.2);<br>  border-color: #4caf50;<br>}<br><br>.custom-error {<br>  background-color: rgba(244, 67, 54, 0.2);<br>  border-color: #f44336;<br>}<br><br>.custom-info {<br>  background-color: rgba(238, 165, 6, 0.2);<br>  border-color: #eea506;<br>}</pre><h3>Conclusion</h3><p>In this blog, we built a reusable and flexible <strong>Toast Notification System</strong> in React using <strong>Context API</strong> and <strong>React Hooks</strong>. We created a provider to manage the notification state, a container to display the notifications, and a demo component to trigger notifications. With this approach, notifications can easily be added anywhere in your React app, and the system is scalable for larger applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b76b182d336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Leetcode Problems | Part 1]]></title>
            <link>https://medium.com/@ksathyareddy7/solving-leetcode-problems-part-1-ce3867cfcf5c?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce3867cfcf5c</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 12:06:56 GMT</pubDate>
            <atom:updated>2023-08-04T12:06:56.218Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello 👋 I am <a href="https://www.sathyareddy.dev/">Sathya Reddy</a> from Hyderabad, India. I am a Senior Frontend Engineer having 5 years of experience building web applications with React, Next, Web3, etc. I love to build elegant, user-friendly interfaces for various devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjBREymqp4erjoW-1MVJDg.png" /></figure><h3><strong>1. Two Sum</strong></h3><p><strong>Problem statement</strong>: Given an array of integers nums and an integer target, return <em>indices of the two numbers such that they add up to </em><em>target</em>. You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> element twice. You can return the answer in any order. <a href="https://leetcode.com/problems/two-sum">https://leetcode.com/problems/two-sum</a></p><p><strong>Solution:</strong></p><pre>export function twoSum(nums: number[], target: number) {<br>  // we will store two index that will equal to target sum<br>  // we start with 0&#39;s as we can&#39;t use the same element twice and target<br>  // should be sum of two different numbers<br>  let answer = [0, 0];<br>  // we will loop over the array, pick one elment at a time<br>  for (let i = 0; i &lt; nums.length; i++) {<br>    // we will break the loop if we have two different index in answer array<br>    if (answer[0] != 0 &amp;&amp; answer[1] != 0) {<br>      break;<br>    }<br>    // we will loop over the array from next index of the selected element in the above loop<br>    for (let j = i + 1; j &lt; nums.length; j++) {<br>      // if we find two numbers that equal to target sum we will store their <br>      // indexs in answer array break the loop to stop execution of the program<br>      if (nums[i] + nums[j] == target) {<br>        answer[0] = i;<br>        answer[1] = j;<br>        break;<br>      }<br>    }<br>  }<br>  return answer;<br>}</pre><pre>    public int[] twoSum(int[] nums, int target) {<br>        int[] answer = new int[2];<br>        for(int i = 0; i &lt; nums.length; i++) {<br>            if(answer[0] != 0 &amp;&amp; answer[1] != 0) {<br>                break;<br>            }<br>            for(int j = i + 1; j &lt; nums.length; j++) {<br>                if(nums[i] + nums[j] == target) {<br>                    answer[0] = i;<br>                    answer[1] = j;<br>                    break;<br>                }<br>            }<br>        }<br>        return answer;<br>    }</pre><h3>2. Single Number</h3><p><strong>Problem statement</strong>: Given a <strong>non-empty</strong> array of integers nums, every element appears <em>twice</em> except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. <a href="https://leetcode.com/problems/single-number/">https://leetcode.com/problems/single-number/</a></p><p><strong>Solution:</strong></p><pre>function singleNumber(nums: number[]) {<br>    if (nums.length == 1) {<br>      return nums[0];<br>    }<br>    let result = nums[0];<br>    // As we know XOR operation with 0 gives the same number =&gt; 2 XOR 0 = 2<br>    // 010 XOR 000 = 010<br>    // XOR operation with same number gives 0 =&gt; 2 XOR 2 = 0<br>    // 010 XOR 010 = 000<br>    // each element i in array, we will perform the XOR operation of the element<br>    // with 0, ans will become 0 if the same number is found (as a XOR a = 0) and<br>    // so after the completion of the loop, only element with no duplicate number<br>    // will remain and will be returned as ans.<br>    for (let i = 1; i &lt; nums.length; i++) {<br>      result = result ^ nums[i];<br>    }<br>    return result;<br>}</pre><pre>    public int singleNumber(int[] nums) {<br>        if(nums.length == 1) {<br>            return nums[0];<br>        }<br>        int result = nums[0];<br>        for (int i = 1; i &lt; nums.length; i++) {<br>            result = result ^ nums[i];<br>        }<br>        return result;<br>    }</pre><h3>3. Contains Duplicate</h3><p><strong>Problem statement</strong>: Given an integer array nums, return true if any value appears <strong>at least twice</strong> in the array, and return false if every element is distinct. <a href="https://leetcode.com/problems/contains-duplicate">https://leetcode.com/problems/contains-duplicate</a></p><p><strong>Solution:</strong></p><pre>function containsDuplicate(nums: number[]) {<br>  // set stores all the unique if the size of set and given array doesn&#39;t<br>  // match it means it contains duplicates<br>  return new Set(nums).size !== nums.length;<br>}</pre><pre>    public boolean containsDuplicate(int[] nums) {<br>        HashSet unique = new HashSet&lt;Number&gt;();<br>        // we will store all the unique numbers in the hashset<br>        for(int i = 0; i &lt; nums.length; i++) {<br>            // if the number already exists return true<br>            if(unique.contains(nums[i])) {<br>                return true;<br>            }<br>            // if doesn&#39;t exists store it in the hashset<br>            unique.add(nums[i]);<br>        }<br>        // if the function reaches here it means all the numbers are unique<br>        // and doesn&#39;t <br>        return false;<br>    }</pre><h3>4. Unique Morse Code</h3><p><strong>Problem statement: </strong>International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:</p><ul><li>&#39;a&#39; maps to &quot;.-&quot;,</li><li>&#39;b&#39; maps to &quot;-...&quot;,</li><li>&#39;c&#39; maps to &quot;-.-.&quot;, and so on.</li></ul><p>For convenience, the full table for the 26 letters of the English alphabet is given below:</p><pre>[&quot;.-&quot;,&quot;-...&quot;,&quot;-.-.&quot;,&quot;-..&quot;,&quot;.&quot;,&quot;..-.&quot;,&quot;--.&quot;,&quot;....&quot;,&quot;..&quot;,&quot;.---&quot;,&quot;-.-&quot;,&quot;.-..&quot;,&quot;--&quot;,&quot;-.&quot;,&quot;---&quot;,&quot;.--.&quot;,&quot;--.-&quot;,&quot;.-.&quot;,&quot;...&quot;,&quot;-&quot;,&quot;..-&quot;,&quot;...-&quot;,&quot;.--&quot;,&quot;-..-&quot;,&quot;-.--&quot;,&quot;--..&quot;]</pre><p>Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.</p><ul><li>For example, &quot;cab&quot; can be written as &quot;-.-..--...&quot;, which is the concatenation of &quot;-.-.&quot;, &quot;.-&quot;, and &quot;-...&quot;. We will call such a concatenation the <strong>transformation</strong> of a word.</li></ul><p>Return <em>the number of different </em><strong><em>transformations</em></strong><em> among all words we have</em>. <a href="https://leetcode.com/problems/unique-morse-code-words/">https://leetcode.com/problems/unique-morse-code-words/</a></p><pre>function uniqueMorseRepresentations(words: string[]) {<br>  let letterToMorse = {<br>    a: &quot;.-&quot;,<br>    b: &quot;-...&quot;,<br>    c: &quot;-.-.&quot;,<br>    d: &quot;-..&quot;,<br>    e: &quot;.&quot;,<br>    f: &quot;..-.&quot;,<br>    g: &quot;--.&quot;,<br>    h: &quot;....&quot;,<br>    i: &quot;..&quot;,<br>    j: &quot;.---&quot;,<br>    k: &quot;-.-&quot;,<br>    l: &quot;.-..&quot;,<br>    m: &quot;--&quot;,<br>    n: &quot;-.&quot;,<br>    o: &quot;---&quot;,<br>    p: &quot;.--.&quot;,<br>    q: &quot;--.-&quot;,<br>    r: &quot;.-.&quot;,<br>    s: &quot;...&quot;,<br>    t: &quot;-&quot;,<br>    u: &quot;..-&quot;,<br>    v: &quot;...-&quot;,<br>    w: &quot;.--&quot;,<br>    x: &quot;-..-&quot;,<br>    y: &quot;-.--&quot;,<br>    z: &quot;--..&quot;,<br>  };<br>  // set stores only unique values<br>  let set = new Set();<br>  for (let i = 0; i &lt; words.length; i++) {<br>    // build morse string for each word and store it in set<br>    let sb = &quot;&quot;, word = words[i];<br>    for (let j = 0; j &lt; word.length; j++) {<br>      sb += letterToMorse[word[j]];<br>    }<br>    set.add(sb);<br>  }<br>  return set.size;<br>};</pre><pre>    public int uniqueMorseRepresentations(String[] words) {<br>        String morseCodes[] = {<br>            &quot;.-&quot;,&quot;-...&quot;,&quot;-.-.&quot;,&quot;-..&quot;,&quot;.&quot;,&quot;..-.&quot;,&quot;--.&quot;,&quot;....&quot;,&quot;..&quot;,&quot;.---&quot;,&quot;-.-&quot;,&quot;.-..&quot;,<br>            &quot;--&quot;,&quot;-.&quot;,&quot;---&quot;,&quot;.--.&quot;,&quot;--.-&quot;,&quot;.-.&quot;,&quot;...&quot;,&quot;-&quot;,&quot;..-&quot;,&quot;...-&quot;,&quot;.--&quot;,&quot;-..-&quot;,<br>            &quot;-.--&quot;,&quot;--..&quot;<br>            };<br>        HashMap&lt;Character, String&gt; letterToMorse = new HashMap&lt;&gt;();<br>        // loop over alphabets and store their morse code against it<br>        for(char i = &#39;a&#39;; i&lt;=&#39;z&#39;; i++){<br>            letterToMorse.put(i,morseCodes[i-&#39;a&#39;]);<br>        }<br><br>        HashSet&lt;String&gt; set = new HashSet&lt;&gt;();<br>        for(int i=0; i&lt;words.length; i++){<br>            // build morse string for each word and store it in set<br>            StringBuilder sb = new StringBuilder();<br>            for(int j=0; j&lt;words[i].length(); j++){<br>                sb.append(letterToMorse.get(words[i].charAt(j)));<br>            }<br>            set.add(sb.toString());<br>        }<br>        return set.size();<br>    }</pre><h3>5. Flipping an Image</h3><p><strong>Problem statement: </strong>Given an n x n binary matrix image, flip the image <strong>horizontally</strong>, then invert it, and return <em>the resulting image</em>.</p><p>To flip an image horizontally means that each row of the image is reversed.</p><ul><li>For example, flipping [1,1,0] horizontally results in [0,1,1].</li></ul><p>To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.</p><ul><li>For example, inverting [0,1,1] results in [1,0,0]. <a href="https://leetcode.com/problems/flipping-an-image/">https://leetcode.com/problems/flipping-an-image/</a></li></ul><p><strong>Solution:</strong></p><pre>function flipAndInvertImage(image: number[][]) {<br>  // map over the outer array, for each inner array reverse it and flip the value<br>  return image.map((row) =&gt; row.reverse().map((i) =&gt; +!i));<br>};</pre><pre>    public int[][] flipAndInvertImage(int[][] image) {<br>        // create output variable<br>        int [][] a = new int[image.length][image[0].length];<br>        // loop over outer array<br>        for(int i = 0; i &lt; image.length; i++){<br>            // for each inner array iterate in reverse and flips the values<br>            for(int j = 0; j &lt; image[i].length; j++){<br>                if(image[i][image[i].length-1-j] == 1){<br>                   a[i][j] = 0;<br>               } else {<br>                 a[i][j] = 1;   <br>               }<br>            }<br>        }        <br>        return a;<br>    }</pre><p>Checkout my portfolio: <a href="https://www.sathyareddy.dev/">Sathya Reddy</a></p><p>Checkout my linkedIn: <a href="https://www.linkedin.com/in/ksathyareddy7">Sathya Reddy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce3867cfcf5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS State Management: Best Tools and Techniques]]></title>
            <link>https://medium.com/@ksathyareddy7/reactjs-state-management-best-tools-and-techniques-90136287e871?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/90136287e871</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Sat, 13 May 2023 08:31:43 GMT</pubDate>
            <atom:updated>2023-05-13T08:59:31.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, my name is <a href="https://www.sathyareddy.dev/">Sathya Reddy</a>, located in Hyderabad, India. I’m a <a href="https://www.sathyareddy.dev/">Lead Engineer</a> at <a href="https://www.linkedin.com/in/ksathyareddy7/">Rapid Innovation</a> a blockchain service-based company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UHcIGysRoMIjOkuAIakGA.png" /></figure><h4>1. React Context API</h4><p>The React Context API is a built-in feature of ReactJS that provides a way to share data between components without the need for props drilling.</p><p>The Context API works by creating a context object that contains the shared data. This context object is then passed down the component tree using a provider component. Any component that needs to access the shared data can use a consumer component to access the data from the context.</p><p>Here’s an example of how the React Context API can be used to manage state in a simple ReactJS application:</p><pre>import React, { createContext, useState, useContext } from &#39;react&#39;;<br><br>// Create a context object<br>const CounterContext = createContext();<br><br>// Create a provider component that sets the initial state<br>const CounterProvider = ({ children }) =&gt; {<br>  const [count, setCount] = useState(0);<br>  const increment = () =&gt; setCount(count + 1);<br>  const decrement = () =&gt; setCount(count - 1);<br><br>  // Pass the state and methods as values to the context<br>  return (<br>    &lt;CounterContext.Provider value={{ count, increment, decrement }}&gt;<br>      {children}<br>    &lt;/CounterContext.Provider&gt;<br>  );<br>};<br><br>// Create a consumer component that uses the context to access the state<br>const Counter = () =&gt; {<br>  const { count, increment, decrement } = useContext(CounterContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Render the application using the provider and consumer components<br>const App = () =&gt; {<br>  return (<br>    &lt;CounterProvider&gt;<br>      &lt;Counter /&gt;<br>    &lt;/CounterProvider&gt;<br>  );<br>};</pre><p>In this example, we create a context object called CounterContext and use it to store the count state and two methods for incrementing and decrementing the count. We then create a provider component called CounterProvider that sets the initial state and passes it down the component tree using the CounterContext.Provider. Finally, we create a consumer component called Counter that uses the useContext hook to access the count state and methods from the CounterContext.</p><p>By using the React Context API, we can avoid the need to pass the count state and methods down through multiple levels of components using props. Instead, we can simply access the data from the context wherever it is needed in the component tree. This makes it a simple and efficient tool for managing state in small to medium-sized applications.</p><h4>2. Redux</h4><p>Redux is a popular tool for managing state in ReactJS applications. Redux is a predictable state container that helps manage complex state in large applications.</p><p>Redux works by storing the application state in a single store object. Components can dispatch actions to update the state in the store, and the store will then trigger a re-render of any components that are subscribed to changes in the relevant parts of the state.</p><p>Here’s an example of how Redux can be used to manage state in a simple ReactJS application:</p><pre>import { createStore } from &#39;redux&#39;;<br>import { Provider, useDispatch, useSelector } from &#39;react-redux&#39;;<br><br>// Define the initial state<br>const initialState = { count: 0 };<br><br>// Define the reducer function<br>const counterReducer = (state = initialState, action) =&gt; {<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>      return state;<br>  }<br>};<br><br>// Create the Redux store<br>const store = createStore(counterReducer);<br><br>// Create the Counter component<br>const Counter = () =&gt; {<br>  const dispatch = useDispatch();<br>  const count = useSelector((state) =&gt; state.count);<br><br>  const handleIncrement = () =&gt; dispatch({ type: &#39;INCREMENT&#39; });<br>  const handleDecrement = () =&gt; dispatch({ type: &#39;DECREMENT&#39; });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={handleIncrement}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={handleDecrement}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Render the application using the Provider component<br>const App = () =&gt; {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;Counter /&gt;<br>    &lt;/Provider&gt;<br>  );<br>};</pre><p>we use the useDispatch hook to get a reference to the dispatch function of the Redux store. We also use the useSelector hook to get access to the count state from the store.</p><p>Inside the Counter component, we define handleIncrement and handleDecrement functions that dispatch the corresponding actions to the store using the dispatch function. We then use the count variable returned by useSelector to display the current count state in the component. we can directly access the state and dispatch functions using the useSelector and useDispatch hooks, respectively.</p><h4>3. Mobx</h4><p>Mobx is a state management library that provides a simple way to manage the application state and keep it in sync with the user interface. It uses the concept of observables to automatically update components whenever a change occurs in the state. Mobx can be a good choice for larger applications with more complex state requirements, or for situations where the Context API might not be sufficient.</p><pre>import { observable, action, makeObservable } from &#39;mobx&#39;;<br>import { observer } from &#39;mobx-react&#39;;<br><br>class CounterStore {<br>  count = 0;<br><br>  constructor() {<br>    makeObservable(this, {<br>      count: observable,<br>      increment: action,<br>      decrement: action<br>    });<br>  }<br><br>  increment() {<br>    this.count++;<br>  }<br><br>  decrement() {<br>    this.count--;<br>  }<br>}<br><br>const Counter = observer(() =&gt; {<br>  const { count, increment, decrement } = counterStore;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={increment}&gt;+&lt;/button&gt;<br>      &lt;span&gt;{count}&lt;/span&gt;<br>      &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>});<br><br>export default Counter;</pre><p>In this example, we create a store called CounterStorewith an observable property called count. We also define two actions called incrementand decrementthat update the count value. The makeObservable()function is used to make the store observable and bind the actions to the store instance.</p><p>We use the observer()function from Mobx React to make the Counter component reactive to changes in the store. We also import the counterStore instance and use its properties and actions in the component.</p><p>By using Mobx, we can simplify the process of managing application state in our ReactJS applications. The concept of observables makes it easy to keep the user interface in sync with the state, and the actions provide a clean way of updating the state. Additionally, the Mobx React package provides the observer()function, which helps optimize performance by only re-rendering components when necessary.</p><h4>4. React-Query</h4><p>React Query is a library for managing remote data in React applications. It simplifies the process of fetching, caching, and updating data from APIs or other data sources. In this blog, we will explore the benefits of React Query and demonstrate how to set up and use a store with it.</p><p>Benefits of React Query:</p><ol><li>Simplified data management: React Query abstracts away the complexity of data management and provides a simple and intuitive way to fetch, cache, and update data.</li><li>Automatic caching: React Query automatically caches the data and updates it when necessary, which reduces the number of API requests and improves performance.</li><li>Optimistic updates: React Query provides the ability to update the cache optimistically, which makes the UI feel faster and more responsive.</li><li>Server-side rendering: React Query works seamlessly with server-side rendering, which makes it easy to render pages on the server and serve them to the client.</li></ol><pre>import { QueryClient, QueryClientProvider, queryCache, useQuery } from &#39;react-query&#39;<br><br>const queryClient = new QueryClient()<br><br>export default function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;Example /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  )<br>}<br><br>function fetchUsers() {<br>  return fetch(&#39;https://jsonplaceholder.typicode.com/users&#39;).then(res =&gt; res.json());<br>}<br><br>function useUsers() {<br>  const queryKey = &#39;users&#39;;<br><br>  const queryFn = () =&gt; fetchUsers();<br><br>  const options = {<br>    onSuccess: data =&gt; queryCache.setQueryData(queryKey, data),<br>    cacheTime: 10000<br>  };<br><br>  return useQuery(queryKey, queryFn, options);<br>}<br><br>function Example() {<br> const { data, isLoading, error } = useUsers();<br><br>  if (isLoading) return &#39;Loading...&#39;;<br><br>  if (error) return `Error: ${error.message}`;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Users&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {data.map(user =&gt; (<br>          &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We define a function called fetchUsers that fetches the list of users from the API. We then create a custom hook called userUsersthat uses the userQueryhook from React Query to fetch the data and cache it. We also define some options for the query, such as the onSuccesscallback and the cache time.</p><p>We use the useUsershook from our store to fetch the data and render it in a user interface. We also handle the loading and error states of the query using the isLoading and errorproperties.</p><p>By using React Query with a store, we can simplify the process of managing remote data in our ReactJS applications and take advantage of the benefits it provides, such as automatic caching and optimistic updates.</p><h4>5. Apollo-Client</h4><p>Apollo Client is a powerful GraphQL client for managing remote data in web and mobile applications. In this blog, we will explore the benefits of Apollo Client and demonstrate how to set up and use a store with it.</p><p>Benefits of Apollo Client:</p><ol><li>Simplified data management: Apollo Client abstracts away the complexity of data management and provides a simple and intuitive way to fetch, cache, and update data from a GraphQL API.</li><li>Automatic caching: Apollo Client automatically caches the data and updates it when necessary, which reduces the number of API requests and improves performance.</li><li>Real-time updates: Apollo Client provides the ability to subscribe to real-time updates from the GraphQL API, which makes it easy to keep the UI up-to-date with the latest data.</li><li>Type safety: Apollo Client provides type safety by generating TypeScript types from the GraphQL schema, which makes it easy to write type-safe code and catch errors at compile time.</li></ol><pre>import { ApolloClient, InMemoryCache, gql, useQuery } from &#39;@apollo/client&#39;;<br><br>const client = new ApolloClient({<br>  uri: &#39;https://countries.trevorblades.com/graphql&#39;,<br>  cache: new InMemoryCache()<br>});<br><br>const COUNTRY_QUERY = gql`<br> query Query {<br>  country(code: &quot;BR&quot;) {<br>    name<br>    native<br>    capital<br>    emoji<br>    currency<br>    languages {<br>      code<br>      name<br>    }<br>  }<br>}<br>`;<br><br>async function getCountry() {<br>  const { data } = await client.query({<br>    query: COUNTRY_QUERY,<br>    fetchPolicy: &#39;cache-first&#39;<br>  });<br><br>  return data.users;<br>}<br><br>function Users() {<br>  const { data, loading, error } = useQuery(getCountry, { fetchPolicy: &#39;cache-first&#39; });<br><br>  if (loading) return &#39;Loading...&#39;;<br><br>  if (error) return `Error: ${error.message}`;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Countries&lt;/h1&gt;<br>      &lt;p&gt;{data?.country?.name}&lt;/p&gt;<br>      &lt;p&gt;{data?.country?.capital}&lt;/p&gt;<br>      &lt;p&gt;{data?.country?.currency}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Users;</pre><p>We define a GraphQL query called COUNTRY_QUERYthat fetches information about a specific country. The query fetches the name, native name, capital, emoji, currency, and languages spoken in the country.</p><p>After that, we define a function called getCountrythat uses the Apollo Client to fetch the data and returns it.</p><p>Finally, we use the useQueryhook from Apollo Client to fetch the data and render it in a user interface. We handle the loading and error states of the query using the loading and error properties. Once the data is fetched successfully, we display the name, capital, and currency of the country in the UI.</p><p>If you like what you read few claps and shares would be appreciated. Follow for more such blogs.</p><p>Checkout my portfolio: <a href="https://www.sathyareddy.dev/">https://www.sathyareddy.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90136287e871" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React’s reconciliation algorithm and its benefits.]]></title>
            <link>https://medium.com/@ksathyareddy7/understanding-reacts-reconciliation-algorithm-and-its-benefits-ecd59316ae12?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecd59316ae12</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Fri, 12 May 2023 10:52:45 GMT</pubDate>
            <atom:updated>2023-05-12T10:52:45.390Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, my name is <a href="https://www.sathyareddy.dev/">Sathya Reddy</a>, located in Hyderabad, India. I’m a Lead Engineer at <a href="https://www.rapidinnovation.io/">Rapid Innovation</a> a blockchain service based company.</p><h4>ReactJS Introduction</h4><p>In the world of web development, ReactJS has emerged as a powerful and popular JavaScript library for building user interfaces. One of the key reasons behind its success is the efficient diffing algorithm it employs, which allows for fast and optimized updates to the DOM. In this comprehensive article, we will take a deep dive into the ReactJS diffing algorithm, uncovering its inner workings and exploring how it contributes to the performance of ReactJS applications.</p><h4>Understanding ReactJS Reconciliation Algorithm</h4><p>ReactJS employs a reconciliation process known as “diffing” to determine the minimal set of changes required to update the user interface. The diffing algorithm, also referred to as “Virtual DOM diffing,” is the heart of React’s efficient rendering system. Let’s explore the key steps involved in this process:</p><ol><li><strong>Virtual DOM Representation:</strong><br>ReactJS creates a virtual representation of the DOM, known as the Virtual DOM. This lightweight abstraction mirrors the actual DOM structure and allows React to perform computations and comparisons efficiently.</li><li><strong>Element-Level Comparison:<br></strong>React compares each element in the Virtual DOM to determine if any changes have occurred. It checks for differences in attributes, styles, or content. By focusing only on the elements that have changed, React minimizes the number of updates needed to synchronize the DOM.</li><li><strong>Diffing Strategy:<br></strong>When an update is triggered in a React component, React compares the new Virtual DOM with the previous one to identify the differences. It follows a top-down, depth-first tree traversal strategy to optimize the diffing process.</li><li><strong>Reconciliation:<br></strong>Once the differences have been identified, React applies the necessary updates to the actual DOM. It intelligently calculates the most efficient way to modify the DOM tree, minimizing the number of expensive operations and reflows.<br> <br>ReactJS goes beyond the basic diffing process and incorporates several optimizations to further enhance performance. Let’s explore some of these optimizations:</li><li><strong>Keys:<br></strong>By assigning a unique “key” prop to each element in a list, React can determine if an element has moved, been added, or removed. This optimization avoids unnecessary re-rendering of elements and provides a significant performance boost, especially when dealing with dynamically changing lists.</li><li><strong>Batched Updates:<br></strong>React batches multiple updates together to minimize the number of DOM operations. Instead of performing updates synchronously, React intelligently schedules them to be executed in batches, reducing unnecessary re-renders and improving overall performance.</li><li><strong>Component-Level Diffing:<br></strong>React divides components into smaller, reusable pieces called “components.” When a component updates, React compares the new and previous versions, optimizing the diffing process to only update the necessary sub-components. This approach significantly reduces the overall computational overhead.</li></ol><h4>Benefits of the ReactJS Reconciliation Algorithm</h4><ol><li><strong>Enhanced Performance:<br></strong>The diffing algorithm allows ReactJS to update only the necessary parts of the DOM, resulting in faster rendering and improved overall performance. By avoiding unnecessary updates, React reduces computational overhead and enhances the user experience.</li><li><strong>Developer-Friendly:<br></strong>React’s diffing algorithm simplifies the process of updating the user interface. Developers can focus on writing clean and modular code, relying on React’s efficient diffing algorithm to handle the updates behind the scenes. This streamlines development and improves productivity.</li><li><strong>Virtual DOM Abstraction:<br></strong>The Virtual DOM provides a lightweight representation of the actual DOM, allowing for quick comparisons and computations. This abstraction layer makes ReactJS versatile and adaptable to various environments, including server-side rendering and native mobile applications.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*n1XYpF4TawredVKpiWgFHQ.png" /></figure><h4>Conclusion</h4><p>In conclusion, the ReactJS diffing algorithm is a key factor behind React’s success in the web development landscape. By efficiently determining the minimal set of changes needed to update the user interface, ReactJS offers enhanced performance and a seamless user experience.</p><p>The Virtual DOM, coupled with the diffing strategy, allows ReactJS to intelligently compare the current state with the desired state, identifying only the elements that require updates. This targeted approach minimizes unnecessary DOM manipulations, resulting in faster rendering and optimized performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecd59316ae12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pass by value VS reference]]></title>
            <link>https://medium.com/@ksathyareddy7/pass-by-value-vs-reference-955dbf0a6ea9?source=rss-7eb7ef913f15------2</link>
            <guid isPermaLink="false">https://medium.com/p/955dbf0a6ea9</guid>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[pass-by-reference]]></category>
            <category><![CDATA[pass-by-value]]></category>
            <dc:creator><![CDATA[Sathya Reddy]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 06:34:59 GMT</pubDate>
            <atom:updated>2023-02-01T06:54:48.666Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi folks, my name is <a href="https://www.sathyareddy.dev/">sathya reddy</a>. I’m a Senior Technical Lead at Rapid Innovation which is a service based company in the blockchain space. I have 5 years of experience of working the javascript and it’s libraries. So today I want to talk about a very important programming concept, let’s get started.</p><p><strong>Pass by Value : </strong>In JavaScript, a new copy of the variable is created when it is passed as an argument to a function, and any changes made to the variable doesn’t affect the original variable. Primitive data types are passed by value.</p><p><strong>Pass by reference : </strong>In JavaScript, a reference to the memory location of the variable is passed when it is passed as an argument to a function, and any changes made to the passed variable affects the original variable. Non-primitive data types are passed by reference.</p><p><a href="https://www.javatpoint.com/javascript-data-types">List of primitive vs non-primitive data types.</a></p><p>Let’s go through an example to understand the concept, in the below image we can see there are 2 variables called name and details . We have a function called logPerson that takes 2 arguments passedNameand passedDetails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-08L9zr63ep975T4eOLheQ.png" /></figure><p>On line number 15 and 16 we are logging the name and age variables which are printed on the right side as starting 2 lines.</p><p>On line number 18, we are calling the logPerson function by passing name as the first argument which is a primitive data type represented by variable named passedNamewhich is being modified on line number 11 to the value of paul and details as the second argument which is a non-primitive data type represented by variable named passedDetailswhich is being modified on line number 12 where the age property inside is assigned value of 30 .</p><p>Here name being a primitive data type the variable value is copied and a new variable is created in the function scope when passed as an argument but where as details is a non-primitive data type so the location/reference of the memory is passed to the function as an argument.</p><p>Therefore when passedNameis modified the value of the name variable is not affect as we are modifying newly created variable in the function scope whereas passedDetailsis modified the value of the details variable is affected as we are modifying the original variable. The result of which we can see on the right side as the last 2 lines.</p><p>Here is the link to <a href="https://codesandbox.io/s/pass-by-value-vs-reference-85f5lj?file=/src/index.js">example</a>.</p><p>I hope you understood the concept, if you have any doubt’s feel free to put it in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955dbf0a6ea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>