<?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 Logan Lee on Medium]]></title>
        <description><![CDATA[Stories by Logan Lee on Medium]]></description>
        <link>https://medium.com/@dlrnjstjs?source=rss-f003027f6cbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HVHGEcj4zYyfmDX6vddSgQ.png</url>
            <title>Stories by Logan Lee on Medium</title>
            <link>https://medium.com/@dlrnjstjs?source=rss-f003027f6cbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:07:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dlrnjstjs/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[React Responsive Design: Mobile-First Development Strategy]]></title>
            <link>https://medium.com/@dlrnjstjs/react-responsive-design-mobile-first-development-strategy-5292525fe108?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5292525fe108</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 16:39:55 GMT</pubDate>
            <atom:updated>2025-11-19T16:39:55.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is Responsive Design?</h3><p>Responsive design is a web design approach where layouts automatically adjust to different screen sizes. It enables us to provide optimized experiences across mobile, tablet, and desktop devices.</p><p>While learning React, I’ve come to understand the critical importance of responsive design. A page that only looks good on desktop doesn’t consider the actual user experience across devices.</p><h3>2. Mobile-First Approach</h3><p>Mobile-first is a development strategy where you design for small screens first, then progressively enhance for larger screens. Let’s explore the advantages of this approach.</p><h4>Why Mobile-First?</h4><ul><li><strong>Performance optimization:</strong> Considering mobile constraints first naturally leads to writing optimized code</li><li><strong>Content prioritization:</strong> Small screens require showing only essential content, making information architecture clearer</li><li><strong>Progressive enhancement:</strong> Starting with core functionality and adding features is more stable than removing them</li></ul><h3>3. Setting Up Breakpoints</h3><p>Breakpoints are the specific screen widths where your layout changes. Here are commonly used breakpoints:</p><p><strong>Standard Breakpoints:</strong></p><ul><li><strong>Mobile:</strong> 320px ~ 767px (base styles, no media query)</li><li><strong>Tablet:</strong> 768px ~ 1023px (@media (min-width: 768px))</li><li><strong>Desktop:</strong> 1024px ~ 1439px (@media (min-width: 1024px))</li><li><strong>Wide Screen:</strong> 1440px+ (@media (min-width: 1440px))</li></ul><h4>Managing Breakpoints with CSS Variables</h4><p>Using CSS variables allows consistent breakpoint management:</p><pre>/* styles/breakpoints.css */<br>:root {<br>  --mobile: 320px;<br>  --tablet: 768px;<br>  --desktop: 1024px;<br>  --wide: 1440px;<br>}<br><br>/* Base mobile styles */<br>.container {<br>  padding: 16px;<br>  font-size: 14px;<br>}<br><br>/* Tablet and up */<br>@media (min-width: 768px) {<br>  .container {<br>    padding: 24px;<br>    font-size: 16px;<br>  }<br>}<br><br>/* Desktop and up */<br>@media (min-width: 1024px) {<br>  .container {<br>    padding: 32px;<br>    max-width: 1200px;<br>    margin: 0 auto;<br>  }<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>Declaring variables in :root makes them reusable throughout the project</li><li>Mobile styles are written as base styles (without media queries)</li><li>min-width is used to progressively enhance for larger screens</li><li>Notice how padding increases progressively (16px → 24px → 32px)</li></ul><h3>4. CSS Responsive Techniques</h3><h4>4.1 Creating Responsive Layouts with Flexbox</h4><p>Flexbox is fundamental for responsive layouts. Let’s look at a navigation menu example:</p><pre>/* MobileFirstNav.css */<br>.nav {<br>  display: flex;<br>  flex-direction: column; /* Mobile: stack vertically */<br>  gap: 8px;<br>}<br><br>.nav-item {<br>  padding: 12px;<br>  text-align: center;<br>}<br><br>@media (min-width: 768px) {<br>  .nav {<br>    flex-direction: row; /* Tablet+: arrange horizontally */<br>    justify-content: space-between;<br>  }<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>On mobile, menu items stack vertically with flex-direction: column</li><li>From tablet up, they arrange horizontally with flex-direction: row</li><li>The gap property maintains uniform spacing between items</li></ul><h4>4.2 Building Complex Layouts with Grid</h4><p>CSS Grid is ideal for complex layouts like product listings:</p><pre>/* ProductGrid.css */<br>.product-grid {<br>  display: grid;<br>  grid-template-columns: 1fr; /* Mobile: 1 column */<br>  gap: 16px;<br>  padding: 16px;<br>}<br><br>@media (min-width: 768px) {<br>  .product-grid {<br>    grid-template-columns: repeat(2, 1fr); /* Tablet: 2 columns */<br>    gap: 24px;<br>  }<br>}<br><br>@media (min-width: 1024px) {<br>  .product-grid {<br>    grid-template-columns: repeat(4, 1fr); /* Desktop: 4 columns */<br>    gap: 32px;<br>  }<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>Mobile: 1fr (1 item per row)</li><li>Tablet: repeat(2, 1fr) (2 items per row)</li><li>Desktop: repeat(4, 1fr) (4 items per row)</li><li>Gap increases as screen size grows</li></ul><h4>4.3 Using Relative Units</h4><p>Using relative units instead of fixed sizes creates flexible layouts:</p><pre>.responsive-text {<br>  /* Not recommended: fixed size */<br>  /* font-size: 16px; */<br>  <br>  /* Recommended: relative size */<br>  font-size: clamp(14px, 4vw, 20px);<br>  /* min 14px, 4% of viewport, max 20px */<br>  <br>  width: min(100%, 1200px);<br>  /* smaller of 100% or 1200px */<br>  <br>  padding: clamp(16px, 5vw, 48px);<br>  /* auto-adjusts between 16px and 48px based on screen size */<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>clamp(min, preferred, max): automatically adjusts size without media queries</li><li>vw (viewport width): percentage of screen width</li><li>min(): selects the smallest value from given options</li></ul><h3>5. Detecting Screen Size with React Hooks</h3><p>Sometimes CSS alone isn’t sufficient. When you need to render completely different components based on screen size, custom Hooks can help.</p><p><strong>Implementing useWindowSize Hook</strong></p><pre>// hooks/useWindowSize.js<br>import { useState, useEffect } from &#39;react&#39;;<br><br>export const useWindowSize = () =&gt; {<br>  // Initialize state<br>  const [windowSize, setWindowSize] = useState({<br>    width: typeof window !== &#39;undefined&#39; ? window.innerWidth : 0,<br>    height: typeof window !== &#39;undefined&#39; ? window.innerHeight : 0,<br>  });<br><br>  useEffect(() =&gt; {<br>    // Window resize handler<br>    const handleResize = () =&gt; {<br>      setWindowSize({<br>        width: window.innerWidth,<br>        height: window.innerHeight,<br>      });<br>    };<br><br>    // Register resize event listener<br>    window.addEventListener(&#39;resize&#39;, handleResize);<br><br>    // Cleanup: remove listener on unmount<br>    return () =&gt; window.removeEventListener(&#39;resize&#39;, handleResize);<br>  }, []);<br><br>  return windowSize;<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>useState manages current window dimensions as state</li><li>useEffect listens for resize events</li><li>State updates whenever window size changes</li><li>Cleanup function removes event listener to prevent memory leaks</li><li>typeof window !== &#39;undefined&#39; check prevents errors in SSR environments</li></ul><h4>Implementing useMediaQuery Hook</h4><p>A more practical media query Hook can be created:</p><pre>// hooks/useMediaQuery.js<br>import { useState, useEffect } from &#39;react&#39;;<br><br>export const useMediaQuery = (query) =&gt; {<br>  const [matches, setMatches] = useState(false);<br><br>  useEffect(() =&gt; {<br>    // Create media query object<br>    const media = window.matchMedia(query);<br>    <br>    // Set initial value<br>    if (media.matches !== matches) {<br>      setMatches(media.matches);<br>    }<br><br>    // Listener for media query changes<br>    const listener = () =&gt; setMatches(media.matches);<br>    <br>    // Register event listener (considering browser compatibility)<br>    if (media.addEventListener) {<br>      media.addEventListener(&#39;change&#39;, listener);<br>    } else {<br>      media.addListener(listener);<br>    }<br><br>    // Cleanup<br>    return () =&gt; {<br>      if (media.removeEventListener) {<br>        media.removeEventListener(&#39;change&#39;, listener);<br>      } else {<br>        media.removeListener(listener);<br>      }<br>    };<br>  }, [matches, query]);<br><br>  return matches;<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>Uses window.matchMedia() to leverage CSS media queries in JavaScript</li><li>Returns true when media query matches, false otherwise</li><li>Handles both addEventListener and addListener for older browser support</li></ul><h4>Hook Usage Example</h4><pre>// components/ResponsiveNav.jsx<br>import { useMediaQuery } from &#39;../hooks/useMediaQuery&#39;;<br><br>const ResponsiveNav = () =&gt; {<br>  const isTablet = useMediaQuery(&#39;(min-width: 768px)&#39;);<br>  const isDesktop = useMediaQuery(&#39;(min-width: 1024px)&#39;);<br><br>  return (<br>    &lt;nav className=&quot;responsive-nav&quot;&gt;<br>      {/* Mobile: hamburger menu */}<br>      {!isTablet &amp;&amp; &lt;MobileMenu /&gt;}<br>      <br>      {/* Tablet: condensed menu */}<br>      {isTablet &amp;&amp; !isDesktop &amp;&amp; &lt;TabletMenu /&gt;}<br>      <br>      {/* Desktop: full menu */}<br>      {isDesktop &amp;&amp; &lt;DesktopMenu /&gt;}<br>    &lt;/nav&gt;<br>  );<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>useMediaQuery determines current screen size</li><li>Conditional rendering displays different components based on screen size</li><li>Enables completely different UI structures impossible with CSS alone</li></ul><h3>6. Responsive Component Patterns</h3><h4>6.1 Conditional Rendering Pattern</h4><p>Content can be displayed differently based on screen size:</p><pre>// components/ProductCard.jsx<br>import { useMediaQuery } from &#39;../hooks/useMediaQuery&#39;;<br><br>const ProductCard = ({ product }) =&gt; {<br>  const isMobile = useMediaQuery(&#39;(max-width: 767px)&#39;);<br><br>  return (<br>    &lt;div className=&quot;product-card&quot;&gt;<br>      &lt;img src={product.image} alt={product.name} /&gt;<br>      &lt;h3&gt;{product.name}&lt;/h3&gt;<br>      &lt;p className=&quot;price&quot;&gt;${product.price}&lt;/p&gt;<br>      <br>      {/* Mobile: short description only */}<br>      {isMobile ? (<br>        &lt;p className=&quot;description-short&quot;&gt;{product.shortDesc}&lt;/p&gt;<br>      ) : (<br>        /* Desktop: full description + reviews */<br>        &lt;&gt;<br>          &lt;p className=&quot;description-full&quot;&gt;{product.fullDesc}&lt;/p&gt;<br>          &lt;div className=&quot;reviews&quot;&gt;<br>            &lt;span&gt;⭐ {product.rating}&lt;/span&gt;<br>            &lt;span&gt;({product.reviewCount} reviews)&lt;/span&gt;<br>          &lt;/div&gt;<br>        &lt;/&gt;<br>      )}<br>      <br>      &lt;button className=&quot;add-to-cart&quot;&gt;Add to Cart&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>Mobile displays only short description</li><li>Desktop displays full description with reviews</li><li>Fragment (&lt;&gt;) groups multiple elements without unnecessary wrappers</li></ul><h4>6.2 Responsive Container Pattern</h4><p>Reusable responsive containers can be created:</p><pre>// components/ResponsiveContainer.jsx<br>const ResponsiveContainer = ({ children }) =&gt; {<br>  return (<br>    &lt;div className=&quot;responsive-container&quot;&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>/* ResponsiveContainer.css */<br>.responsive-container {<br>  width: 100%;<br>  padding: 0 16px; /* Mobile: 16px sides */<br>  margin: 0 auto;<br>}<br><br>@media (min-width: 768px) {<br>  .responsive-container {<br>    padding: 0 32px; /* Tablet: 32px sides */<br>    max-width: 1200px; /* limit maximum width */<br>  }<br>}<br><br>@media (min-width: 1440px) {<br>  .responsive-container {<br>    max-width: 1400px; /* Wider on large screens */<br>  }<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>Container wraps all page content</li><li>Padding and max-width automatically adjust based on screen size</li><li>max-width prevents content from stretching excessively on large screens</li></ul><h4>6.3 Responsive Grid Pattern</h4><p>Automatically responsive grids can be created without media queries:</p><pre>// components/ResponsiveGrid.jsx<br>const ResponsiveGrid = ({ children, minWidth = &#39;280px&#39; }) =&gt; {<br>  return (<br>    &lt;div <br>      className=&quot;responsive-grid&quot;<br>      style={{<br>        display: &#39;grid&#39;,<br>        gridTemplateColumns: `repeat(auto-fit, minmax(${minWidth}, 1fr))`,<br>        gap: &#39;clamp(16px, 3vw, 32px)&#39;,<br>      }}<br>    &gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>auto-fit: automatically adjusts column count to fit screen</li><li>minmax(280px, 1fr): each item is minimum 280px, remaining space distributed equally</li><li>Fully responsive without media queries</li><li>minWidth prop allows minimum width customization</li></ul><p>Usage example:</p><pre>// pages/ProductList.jsx<br>const ProductList = () =&gt; {<br>  return (<br>    &lt;ResponsiveGrid minWidth=&quot;300px&quot;&gt;<br>      {products.map(product =&gt; (<br>        &lt;ProductCard key={product.id} product={product} /&gt;<br>      ))}<br>    &lt;/ResponsiveGrid&gt;<br>  );<br>};</pre><h3>7. Handling Responsive Images</h3><p>Images significantly impact page loading speed. Image optimization is especially crucial in mobile environments.</p><h4>7.1 Using srcset and sizes Attributes</h4><pre>// components/ResponsiveImage.jsx<br>const ResponsiveImage = ({ alt, baseUrl, imageName }) =&gt; {<br>  return (<br>    &lt;img<br>      src={`${baseUrl}/${imageName}-800w.jpg`}<br>      srcSet={`<br>        ${baseUrl}/${imageName}-400w.jpg 400w,<br>        ${baseUrl}/${imageName}-800w.jpg 800w,<br>        ${baseUrl}/${imageName}-1200w.jpg 1200w,<br>        ${baseUrl}/${imageName}-1600w.jpg 1600w<br>      `}<br>      sizes=&quot;<br>        (max-width: 767px) 100vw,<br>        (max-width: 1023px) 50vw,<br>        33vw<br>      &quot;<br>      alt={alt}<br>      loading=&quot;lazy&quot;<br>    /&gt;<br>  );<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>src: default image (fallback for older browsers)</li><li>srcSet: provides multiple image sizes (400w, 800w, 1200w, 1600w)</li><li>sizes: specifies image width at each breakpoint</li><li>Mobile (≤767px): full screen width (100vw)</li><li>Tablet (≤1023px): half screen (50vw)</li><li>Desktop: one-third screen (33vw)</li><li>loading=&quot;lazy&quot;: implements lazy loading to load images only when they enter viewport</li></ul><h4>7.2 Using picture Element</h4><p>Useful when providing completely different images per screen size:</p><pre>const HeroImage = () =&gt; {<br>  return (<br>    &lt;picture&gt;<br>      {/* Mobile: portrait ratio image */}<br>      &lt;source<br>        media=&quot;(max-width: 767px)&quot;<br>        srcSet=&quot;/images/hero-mobile.jpg&quot;<br>      /&gt;<br>      <br>      {/* Tablet: square ratio image */}<br>      &lt;source<br>        media=&quot;(max-width: 1023px)&quot;<br>        srcSet=&quot;/images/hero-tablet.jpg&quot;<br>      /&gt;<br>      <br>      {/* Desktop: landscape ratio image */}<br>      &lt;img<br>        src=&quot;/images/hero-desktop.jpg&quot;<br>        alt=&quot;Hero banner&quot;<br>        style={{ width: &#39;100%&#39;, height: &#39;auto&#39; }}<br>      /&gt;<br>    &lt;/picture&gt;<br>  );<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>picture element can contain multiple source elements</li><li>Browser checks conditions from top to bottom, selecting the first matching image</li><li>Can provide portrait ratio on mobile, landscape ratio on desktop</li></ul><h3>8. Testing Responsive Design</h3><h4>8.1 Using Browser Developer Tools</h4><p>Testing with Chrome DevTools:</p><ol><li>Open DevTools with F12 or Ctrl+Shift+I</li><li>Click Toggle Device Toolbar (Ctrl+Shift+M)</li><li>Select various devices from the top dropdown to test</li><li>Use Responsive mode to manually adjust screen size</li></ol><h4>8.2 Testing on Real Devices</h4><p>Exposing development server to local network:</p><pre>// package.json<br>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite --host&quot;<br>  }<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>Adding --host option makes it accessible from local network</li><li>Access from mobile devices using the Network address shown in terminal (e.g., 192.168.0.10:5173)</li><li>Can test on real mobile devices connected to same Wi-Fi</li></ul><h4>8.3 Development Breakpoint Indicator</h4><p>A component to visually confirm current breakpoint during development:</p><pre>// components/BreakpointIndicator.jsx<br>import { useWindowSize } from &#39;../hooks/useWindowSize&#39;;<br><br>const BreakpointIndicator = () =&gt; {<br>  const { width } = useWindowSize();<br>  <br>  // Determine current breakpoint<br>  const getBreakpoint = () =&gt; {<br>    if (width &lt; 768) return { name: &#39;Mobile&#39;, color: &#39;#ff6b6b&#39; };<br>    if (width &lt; 1024) return { name: &#39;Tablet&#39;, color: &#39;#4ecdc4&#39; };<br>    if (width &lt; 1440) return { name: &#39;Desktop&#39;, color: &#39;#45b7d1&#39; };<br>    return { name: &#39;Wide&#39;, color: &#39;#96ceb4&#39; };<br>  };<br>  <br>  const breakpoint = getBreakpoint();<br>  <br>  // Display only in development<br>  if (process.env.NODE_ENV !== &#39;development&#39;) return null;<br>  <br>  return (<br>    &lt;div style={{<br>      position: &#39;fixed&#39;,<br>      bottom: 20,<br>      right: 20,<br>      padding: &#39;8px 16px&#39;,<br>      backgroundColor: breakpoint.color,<br>      color: &#39;white&#39;,<br>      borderRadius: &#39;8px&#39;,<br>      fontWeight: &#39;bold&#39;,<br>      zIndex: 9999,<br>      boxShadow: &#39;0 2px 8px rgba(0,0,0,0.3)&#39;,<br>    }}&gt;<br>      {breakpoint.name}: {width}px<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>Code Explanation:</strong></p><ul><li>Displays current breakpoint and screen width in bottom-right corner</li><li>Each breakpoint shows in a different color for easy distinction</li><li>Visible only in development, automatically hidden in production</li><li>Updates in real-time as screen size changes</li></ul><p>Adding to App.jsx:</p><pre>// App.jsx<br>import BreakpointIndicator from &#39;./components/BreakpointIndicator&#39;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      {/* Other components... */}<br>      &lt;BreakpointIndicator /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Wrapping Up</h3><p>This article covered implementing responsive design in React. Starting with a mobile-first approach enables creating more systematic and performant web applications.</p><p>From CSS media query basics to advanced patterns using React Hooks, responsive design is an essential element of modern web development. Applying the patterns introduced here to real projects will deepen your understanding of responsive design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5292525fe108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React PWA: Creating a Web App That Feels Native]]></title>
            <link>https://medium.com/@dlrnjstjs/building-a-react-pwa-creating-a-web-app-that-feels-native-57bd21ec03e5?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/57bd21ec03e5</guid>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 16:13:39 GMT</pubDate>
            <atom:updated>2025-11-12T16:13:39.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What Exactly is a PWA?</h3><p>While studying web development, I kept hearing about PWA (Progressive Web App). At first, I thought “Isn’t it just a website?” But after building one myself, I realized it’s actually quite amazing.</p><p>Simply put, a PWA is <strong>a website that works like a native app</strong>. You can add it to your home screen, it works offline, and it can even send push notifications. The best part? No need to submit to app stores — users can access it directly through a URL.</p><p>Big services like Twitter (X), Instagram, and Starbucks all run PWAs!</p><h3>2. The 3 Core Elements of PWA</h3><p>To build a PWA, you need three essential components:</p><p><strong>HTTPS (Security Connection)</strong> — Required for PWA functionality. This ensures secure data transmission between users and your server.</p><p><strong>Service Worker</strong> — This is the brain of your PWA. It handles offline functionality, caching, and background tasks. Think of it as a proxy between your browser and the server.</p><p><strong>Web App Manifest</strong> — This is a JSON file that contains information about your app: name, icons, theme colors, and how it should be displayed. It’s what makes your web app installable.</p><p>Get these three right, and you’ve got yourself a basic PWA!</p><h3>3. Setting Up Your React Project</h3><p>There are two main ways to build a React PWA: using Create React App or Vite. I went with Vite since it’s the modern approach and much faster.</p><h4>Creating a React Project with Vite</h4><pre>npm create vite@latest my-pwa-app -- --template react<br>cd my-pwa-app<br>npm install</pre><p>What these commands do:</p><ul><li>npm create vite@latest: Creates a project using the latest version of Vite</li><li>my-pwa-app: This is our project name</li><li>--template react: Tells Vite we want to use the React template</li><li>npm install: Downloads all necessary packages</li></ul><h4>Installing the PWA Plugin</h4><pre>npm install vite-plugin-pwa -D</pre><p>The vite-plugin-pwa makes it super easy to create PWAs in Vite. The -D flag installs it as a development dependency.</p><h4>Configuring Vite</h4><p>Open vite.config.js and modify it like this:</p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br>import { VitePWA } from &#39;vite-plugin-pwa&#39;<br><br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    VitePWA({<br>      registerType: &#39;autoUpdate&#39;,  // Automatically update Service Worker<br>      includeAssets: [&#39;favicon.ico&#39;, &#39;robots.txt&#39;, &#39;apple-touch-icon.png&#39;],  // Files to cache<br>      manifest: {<br>        name: &#39;My First PWA&#39;,  // Full app name<br>        short_name: &#39;PWA App&#39;,  // Short name displayed on home screen<br>        description: &#39;My first Progressive Web App built with React&#39;,<br>        theme_color: &#39;#ffffff&#39;,  // Color of the top bar<br>        background_color: &#39;#ffffff&#39;,  // Splash screen background color<br>        display: &#39;standalone&#39;,  // Makes it look like a native app (hides browser UI)<br>        icons: [<br>          {<br>            src: &#39;pwa-192x192.png&#39;,  // Small icon<br>            sizes: &#39;192x192&#39;,<br>            type: &#39;image/png&#39;<br>          },<br>          {<br>            src: &#39;pwa-512x512.png&#39;,  // Large icon<br>            sizes: &#39;512x512&#39;,<br>            type: &#39;image/png&#39;,<br>            purpose: &#39;any maskable&#39;  // Works in various environments<br>          }<br>        ]<br>      }<br>    })<br>  ]<br>})</pre><p>What each setting does:</p><ul><li>registerType: &#39;autoUpdate&#39;: Automatically updates when a new version is available</li><li>includeAssets: Specifies which static files to include in the cache</li><li>manifest: Contains app information like name, icons, and colors</li><li>display: &#39;standalone&#39;: When the app opens, it won&#39;t show the browser&#39;s address bar, making it look like a native app</li></ul><h3>4. Registering the Service Worker</h3><p>The Service Worker is the heart of your PWA. It sits between your browser and server, intercepting network requests, managing caching, and providing offline functionality.</p><p>Luckily, vite-plugin-pwa automatically generates the Service Worker, but you can also customize it.</p><h4>Basic Service Worker Registration</h4><p>Add this code to your src/main.jsx file:</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App.jsx&#39;<br>import &#39;./index.css&#39;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>)<br><br>// Service Worker registration<br>if (&#39;serviceWorker&#39; in navigator) {<br>  // Check if browser supports Service Worker<br>  window.addEventListener(&#39;load&#39;, () =&gt; {<br>    // Execute after page is fully loaded<br>    navigator.serviceWorker.register(&#39;/sw.js&#39;)<br>      .then(registration =&gt; {<br>        console.log(&#39;SW registered: &#39;, registration);<br>        // Registration successful<br>      })<br>      .catch(registrationError =&gt; {<br>        console.log(&#39;SW registration failed: &#39;, registrationError);<br>        // Registration failed<br>      });<br>  });<br>}</pre><p>Code explanation:</p><ul><li>&#39;serviceWorker&#39; in navigator: Checks if the current browser supports Service Workers</li><li>window.addEventListener(&#39;load&#39;): Waits until the page is fully loaded to avoid impacting initial loading performance</li><li>navigator.serviceWorker.register(&#39;/sw.js&#39;): Registers the Service Worker file</li><li>.then() and .catch(): Handle success and failure cases</li></ul><h3>5. Configuring the Manifest File</h3><p>We configured the manifest in vite.config.js earlier, but let&#39;s dive deeper into what each property means.</p><h4>Preparing Your Icons</h4><p>PWAs need icons in various sizes. Place these icons in your public folder:</p><p><strong>pwa-192x192.png</strong> (192×192 pixels) — Standard icon used for most situations</p><p><strong>pwa-512x512.png</strong> (512×512 pixels) — High-resolution icon for larger displays and splash screens</p><p><strong>apple-touch-icon.png</strong> (180×180 pixels) — Specifically for iOS devices when users add your app to their home screen</p><h4>Deep Dive into Manifest Properties</h4><pre>manifest: {<br>  name: &#39;My First PWA&#39;,<br>  // The full name of your app. Shown in installation prompts and app info<br>  <br>  short_name: &#39;PWA App&#39;,<br>  // Short name displayed on home screen or app launcher<br>  // Best to keep it under 12 characters<br>  <br>  description: &#39;My first Progressive Web App built with React&#39;,<br>  // Description of your app. Appears in search and app info<br>  <br>  start_url: &#39;/&#39;,<br>  // The URL to load when the app starts<br>  <br>  theme_color: &#39;#ffffff&#39;,<br>  // Color of the browser&#39;s address bar and task switcher<br>  <br>  background_color: &#39;#ffffff&#39;,<br>  // Background color of the splash screen while app is loading<br>  <br>  display: &#39;standalone&#39;,<br>  // How the app should be displayed<br>  // standalone: Like a native app (recommended)<br>  // fullscreen: Full screen mode<br>  // minimal-ui: Minimal browser UI<br>  // browser: Regular browser mode<br>  <br>  orientation: &#39;portrait&#39;,<br>  // Lock screen orientation<br>  // portrait: vertical, landscape: horizontal, any: automatic<br>  <br>  icons: [...]<br>  // Array of icons in different sizes<br>}</pre><h3>6. Implementing Offline Functionality</h3><p>One of the coolest features of PWA is offline functionality. Let’s make our app work even when the internet is disconnected!</p><h4>Setting Up Caching Strategies</h4><p>Add caching strategies to your vite.config.js:</p><pre>VitePWA({<br>  registerType: &#39;autoUpdate&#39;,<br>  workbox: {<br>    // Workbox is Google&#39;s Service Worker library<br>    globPatterns: [&#39;**/*.{js,css,html,ico,png,svg,woff2}&#39;],<br>    // Specifies file patterns to cache<br>    // ** means all directories, * means all files<br>    <br>    runtimeCaching: [<br>      {<br>        // API request caching<br>        urlPattern: /^https:\/\/api\.example\.com\/.*/i,<br>        // Caches API requests matching this pattern<br>        <br>        handler: &#39;NetworkFirst&#39;,<br>        // NetworkFirst: Try network first, use cache if it fails<br>        // CacheFirst: Check cache first, make network request if not found<br>        // StaleWhileRevalidate: Show cache first, update in background<br>        <br>        options: {<br>          cacheName: &#39;api-cache&#39;,<br>          // Name for this cache<br>          <br>          expiration: {<br>            maxEntries: 50,<br>            // Store maximum of 50 items in cache<br>            maxAgeSeconds: 60 * 60 * 24,<br>            // Cache expires after 24 hours (86400 seconds)<br>          },<br>          <br>          cacheableResponse: {<br>            statuses: [0, 200],<br>            // Only cache status codes 0 (CORS) and 200 (success)<br>          }<br>        }<br>      },<br>      {<br>        // Image caching<br>        urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp)$/,<br>        // Cache requests for image file extensions<br>        <br>        handler: &#39;CacheFirst&#39;,<br>        // Images don&#39;t change often, so prioritize cache<br>        <br>        options: {<br>          cacheName: &#39;images-cache&#39;,<br>          expiration: {<br>            maxEntries: 60,<br>            maxAgeSeconds: 30 * 24 * 60 * 60,<br>            // 30 days<br>          }<br>        }<br>      }<br>    ]<br>  },<br>  manifest: {<br>    // ... previous manifest configuration<br>  }<br>})</pre><h4>Creating an Offline Fallback Page</h4><p>Let’s create a page to show when the internet is disconnected.</p><p>Create src/components/Offline.jsx:</p><pre>import React from &#39;react&#39;;<br><br>function Offline() {<br>  return (<br>    &lt;div style={{<br>      display: &#39;flex&#39;,<br>      flexDirection: &#39;column&#39;,<br>      alignItems: &#39;center&#39;,<br>      justifyContent: &#39;center&#39;,<br>      height: &#39;100vh&#39;,<br>      textAlign: &#39;center&#39;,<br>      padding: &#39;20px&#39;<br>    }}&gt;<br>      &lt;h1&gt;🔌 Offline Mode&lt;/h1&gt;<br>      &lt;p&gt;Please check your internet connection.&lt;/p&gt;<br>      &lt;p&gt;Some features are still available offline.&lt;/p&gt;<br>      &lt;button <br>        onClick={() =&gt; window.location.reload()}<br>        style={{<br>          marginTop: &#39;20px&#39;,<br>          padding: &#39;10px 20px&#39;,<br>          fontSize: &#39;16px&#39;,<br>          cursor: &#39;pointer&#39;<br>        }}<br>      &gt;<br>        Try Again<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Offline;</pre><h4>Detecting Online/Offline Status</h4><p>Let’s create a custom hook in src/hooks/useOnlineStatus.js:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useOnlineStatus() {<br>  // Manage current online status with state<br>  const [isOnline, setIsOnline] = useState(navigator.onLine);<br>  <br>  useEffect(() =&gt; {<br>    // Function to execute when switching to online<br>    function handleOnline() {<br>      setIsOnline(true);<br>      console.log(&#39;Internet connection restored!&#39;);<br>    }<br>    <br>    // Function to execute when switching to offline<br>    function handleOffline() {<br>      setIsOnline(false);<br>      console.log(&#39;Internet connection lost.&#39;);<br>    }<br>    <br>    // Register event listeners<br>    // These functions execute when browser detects online/offline status changes<br>    window.addEventListener(&#39;online&#39;, handleOnline);<br>    window.addEventListener(&#39;offline&#39;, handleOffline);<br>    <br>    // Remove event listeners when component unmounts<br>    // This is essential to prevent memory leaks<br>    return () =&gt; {<br>      window.removeEventListener(&#39;online&#39;, handleOnline);<br>      window.removeEventListener(&#39;offline&#39;, handleOffline);<br>    };<br>  }, []); // Empty array: execute once when component mounts<br>  <br>  return isOnline;<br>}<br><br>export default useOnlineStatus;</pre><h4>Using It in Your App</h4><p>Modify src/App.jsx:</p><pre>import React from &#39;react&#39;;<br>import useOnlineStatus from &#39;./hooks/useOnlineStatus&#39;;<br>import Offline from &#39;./components/Offline&#39;;<br><br>function App() {<br>  const isOnline = useOnlineStatus();<br>  <br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      {/* Online status banner */}<br>      {!isOnline &amp;&amp; (<br>        &lt;div style={{<br>          position: &#39;fixed&#39;,<br>          top: 0,<br>          width: &#39;100%&#39;,<br>          backgroundColor: &#39;#ff6b6b&#39;,<br>          color: &#39;white&#39;,<br>          padding: &#39;10px&#39;,<br>          textAlign: &#39;center&#39;,<br>          zIndex: 1000<br>        }}&gt;<br>          ⚠️ You are currently offline<br>        &lt;/div&gt;<br>      )}<br>      <br>      {/* Show Offline component when offline */}<br>      {!isOnline ? (<br>        &lt;Offline /&gt;<br>      ) : (<br>        &lt;&gt;<br>          &lt;h1&gt;My First PWA&lt;/h1&gt;<br>          &lt;p&gt;You&#39;re online! All features are available.&lt;/p&gt;<br>          {/* Add the rest of your app content here */}<br>        &lt;/&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>7. Adding an Install Prompt</h3><p>Let’s create an install button that allows users to add the PWA to their home screen.</p><h4>Creating the Install Component</h4><p>src/components/InstallPrompt.jsx:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function InstallPrompt() {<br>  // State to store the install prompt<br>  const [deferredPrompt, setDeferredPrompt] = useState(null);<br>  // State to decide whether to show the install button<br>  const [showInstall, setShowInstall] = useState(false);<br>  <br>  useEffect(() =&gt; {<br>    // Listen for the beforeinstallprompt event<br>    // This event fires when the browser determines the PWA can be installed<br>    const handler = (e) =&gt; {<br>      // Prevent the browser&#39;s default install prompt<br>      e.preventDefault();<br>      <br>      // Save the event object for later use<br>      setDeferredPrompt(e);<br>      <br>      // Show our custom install button<br>      setShowInstall(true);<br>      <br>      console.log(&#39;PWA installation available!&#39;);<br>    };<br>    <br>    window.addEventListener(&#39;beforeinstallprompt&#39;, handler);<br>    <br>    return () =&gt; window.removeEventListener(&#39;beforeinstallprompt&#39;, handler);<br>  }, []);<br>  <br>  // Install button click handler<br>  const handleInstall = async () =&gt; {<br>    if (!deferredPrompt) {<br>      return;<br>    }<br>    <br>    // Trigger the saved install prompt<br>    deferredPrompt.prompt();<br>    <br>    // Wait for the user&#39;s choice<br>    const { outcome } = await deferredPrompt.userChoice;<br>    <br>    console.log(`User choice: ${outcome}`);<br>    // outcome is either &#39;accepted&#39; or &#39;dismissed&#39;<br>    <br>    if (outcome === &#39;accepted&#39;) {<br>      console.log(&#39;PWA installation completed!&#39;);<br>    } else {<br>      console.log(&#39;PWA installation cancelled&#39;);<br>    }<br>    <br>    // The prompt can only be used once, so reset it<br>    setDeferredPrompt(null);<br>    setShowInstall(false);<br>  };<br>  <br>  // Don&#39;t render anything if we shouldn&#39;t show the install button<br>  if (!showInstall) {<br>    return null;<br>  }<br>  <br>  return (<br>    &lt;div style={{<br>      position: &#39;fixed&#39;,<br>      bottom: &#39;20px&#39;,<br>      right: &#39;20px&#39;,<br>      zIndex: 1000<br>    }}&gt;<br>      &lt;button<br>        onClick={handleInstall}<br>        style={{<br>          backgroundColor: &#39;#4CAF50&#39;,<br>          color: &#39;white&#39;,<br>          padding: &#39;15px 30px&#39;,<br>          border: &#39;none&#39;,<br>          borderRadius: &#39;25px&#39;,<br>          fontSize: &#39;16px&#39;,<br>          cursor: &#39;pointer&#39;,<br>          boxShadow: &#39;0 4px 6px rgba(0,0,0,0.1)&#39;,<br>          display: &#39;flex&#39;,<br>          alignItems: &#39;center&#39;,<br>          gap: &#39;10px&#39;<br>        }}<br>      &gt;<br>        📱 Install App<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default InstallPrompt;</pre><h4>Adding It to Your App</h4><pre>import InstallPrompt from &#39;./components/InstallPrompt&#39;;<br><br>function App() {<br>  // ... existing code<br>  <br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      {/* ... existing code */}<br>      &lt;InstallPrompt /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>8. Testing and Deploying Your PWA</h3><h4>Testing Locally</h4><p>While PWAs only work properly on HTTPS, the local development environment allows <a href="http://localhost/">http://localhost</a> as an exception.</p><pre>npm run dev</pre><p>Start the development server and open it in your browser. However, Service Workers might not work properly in development mode.</p><h4>Testing the Production Build</h4><pre># Create production build<br>npm run build<br><br># Run the built files on a local server<br>npm run preview</pre><p>npm run build creates optimized production files, and npm run preview runs them on a local server.</p><h4>Inspecting with Chrome DevTools</h4><p>Follow these steps in Chrome browser:</p><ol><li>Press F12 to open Developer Tools</li><li>Click the Application tab</li><li>Check the left menu for:</li></ol><ul><li><strong>Manifest</strong>: View manifest.json configuration</li><li><strong>Service Workers</strong>: Check Service Worker status</li><li><strong>Cache Storage</strong>: View cached files</li></ul><p>4. Run Lighthouse audit in the Lighthouse tab</p><ul><li>Check “Progressive Web App” in Categories</li><li>Click “Analyze page load”</li><li>You can see the PWA checklist and areas for improvement</li></ul><h4>Deploying with Vercel</h4><p>The simplest deployment method is using Vercel.</p><pre># Install Vercel CLI<br>npm i -g vercel<br><br># Deploy<br>vercel</pre><p>Alternatively, you can connect your GitHub repository through the Vercel website:</p><ol><li>Go to <a href="https://vercel.com/">vercel.com</a></li><li>Log in with your GitHub account</li><li>Click “New Project”</li><li>Select your GitHub repository</li><li>Click Deploy (settings are automatically detected)</li></ol><p>Once deployment is complete, you’ll get an HTTPS URL, and now all PWA features will work!</p><h4>Post-Deployment Checklist</h4><p><strong>HTTPS</strong> — Verify the URL starts with <a href="https://./">https://.</a> This is mandatory for PWA functionality.</p><p><strong>Installability</strong> — Look for the install icon in the address bar’s right side. If you see it, your PWA can be installed.</p><p><strong>Offline Functionality</strong> — Open DevTools &gt; Network tab &gt; Select “Offline”. The page should still display properly.</p><p><strong>Lighthouse Score</strong> — Run Lighthouse audit (DevTools &gt; Lighthouse). All PWA items should pass.</p><h3>9. What I Learned From Studying This</h3><p>While studying PWAs, I realized they’re not as complicated as I initially thought. Tools like vite-plugin-pwa automate much of the process, making basic implementation quite accessible.</p><p>What impressed me most was the offline functionality. The concept of Service Workers intercepting network requests and using cache was fascinating. The idea of having a middle layer between the browser and server was hard to grasp at first, but writing the code myself helped me understand it.</p><p>Learning about caching strategies was also enlightening. Understanding when to use NetworkFirst, CacheFirst, or StaleWhileRevalidate, and why different strategies work better for API requests versus image requests, taught me that caching isn’t just about “storing things” — it’s about choosing the right strategy for each situation.</p><p>The Manifest file settings also had meaning in every detail. Things like how display: &#39;standalone&#39; hides the browser UI to look like a native app, or how theme_color changes the top bar color — these small details combine to create an app-like experience.</p><h4>Topics I Want to Study Further</h4><p>I studied basic PWA implementation this time, but there are many advanced features I haven’t covered yet:</p><ul><li><strong>Push Notifications</strong> — How to send notifications to users using the Web Push API</li><li><strong>Background Sync</strong> — How to synchronize offline work later using the Background Sync API</li><li><strong>IndexedDB</strong> — How to utilize the browser’s local database</li><li><strong>Advanced Caching Patterns</strong> — More complex caching strategies and optimization techniques</li></ul><p>Through studying PWAs, I learned that web technologies can provide native app-like experiences in a really elegant way. The ability to deploy with just a URL without App Store approval, and letting users try it on the web before deciding to install, seems like a significant advantage.</p><p>I hope this guide helps others learning about PWAs. I plan to continue studying and exploring more advanced topics!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57bd21ec03e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React Design System: Creating a Reusable Component Library]]></title>
            <link>https://medium.com/@dlrnjstjs/building-a-react-design-system-creating-a-reusable-component-library-99fd70a4d6be?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/99fd70a4d6be</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ui-component]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 16:49:09 GMT</pubDate>
            <atom:updated>2025-11-05T16:49:09.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is a Design System?</h3><p>While learning React through self-study and building various projects, it’s common to find yourself repeatedly creating the same buttons and input fields. “I definitely made this button in my last project…” Many developers find themselves copying and pasting code, realizing there must be a better way.</p><p>Simply put, a design system is <strong>a collection of reusable UI components</strong>. Like LEGO blocks, you combine pre-made pieces to create something new. It includes not just components, but also design rules like colors, spacing, and typography.</p><h3>2. Why Do We Need a Design System?</h3><p>Building a design system provides these benefits:</p><p><strong>Maintaining Consistency</strong><br>Button styles and colors remain the same throughout the project. No more blue buttons on one page and green buttons on another.</p><p><strong>Faster Development</strong><br>When building new features, just use the components you’ve already created. No need to spend 30 minutes creating a button from scratch.</p><p><strong>Easier Maintenance</strong><br>When you want to change button styles, modify just one component and it applies across the entire project. No need to manually update 100 files.</p><p><strong>Better Collaboration</strong><br>In team projects, instead of explaining “please make buttons like this” every time, just say “use the Button component” and you’re done.</p><h3>3. Core Components of a Design System</h3><p>Through studying design systems, we can see they’re divided into three main parts:</p><p><strong>Design Tokens</strong><br>Basic design values like colors, spacing, and font sizes. For example: primary-color: #3B82F6, spacing-md: 16px</p><p><strong>Base Components</strong><br>Reusable UI pieces like Button, Input, and Card. Examples: Button, Input, Checkbox, Radio</p><p><strong>Composite Components</strong><br>More complex UI built by combining base components. Examples: Form, Modal, Navigation</p><h3>4. Designing Project Structure</h3><p>First, let’s organize the project folder structure. By referencing various open-source projects, we can create a structure like this:</p><pre>src/<br>├── components/          # Folder containing components<br>│   ├── Button/         # Button component folder<br>│   │   ├── Button.jsx  # Component code<br>│   │   ├── Button.css  # Styles<br>│   │   └── index.js    # Export file<br>│   ├── Input/<br>│   └── Card/<br>├── styles/             # Common styles<br>│   ├── tokens.css      # Design tokens (colors, spacing, etc.)<br>│   └── global.css      # Global styles<br>└── index.js            # Entry point that exports all components</pre><p>The reason for separating each component into folders is that keeping related files (JS, CSS, tests, etc.) together makes management easier.</p><h3>5. Creating Design Tokens</h3><p>Design tokens are the foundation of a design system. By defining colors, spacing, font sizes, etc. as variables, when the design changes later, you only need to modify one place.</p><p><strong>styles/tokens.css</strong></p><pre>/* <br>  Define design tokens using CSS variables.<br>  :root declares variables that apply to the entire HTML.<br>*/<br>:root {<br>  /* <br>    Color definitions<br>    - Primary: Used for main actions (buttons, links, etc.)<br>    - Secondary: Used for secondary actions<br>    - Success: Success messages<br>    - Error: Error messages<br>  */<br>  --color-primary: #3B82F6;        /* Blue - primary color */<br>  --color-primary-hover: #2563EB;  /* Darker blue - on hover */<br>  --color-secondary: #6B7280;      /* Gray - secondary color */<br>  --color-success: #10B981;        /* Green - success */<br>  --color-error: #EF4444;          /* Red - error */<br>  --color-text: #1F2937;           /* Dark gray - default text */<br>  --color-text-light: #6B7280;     /* Light gray - helper text */<br>  --color-background: #FFFFFF;     /* White - background */<br>  --color-border: #E5E7EB;         /* Light gray - borders */<br>  <br>  /* <br>    Spacing definitions<br>    - xs ~ xl: Various sizes of spacing<br>    - Larger numbers mean wider spacing<br>  */<br>  --spacing-xs: 4px;   /* Extra small spacing */<br>  --spacing-sm: 8px;   /* Small spacing */<br>  --spacing-md: 16px;  /* Medium spacing */<br>  --spacing-lg: 24px;  /* Large spacing */<br>  --spacing-xl: 32px;  /* Extra large spacing */<br>  <br>  /* <br>    Font size definitions<br>  */<br>  --font-size-sm: 14px;   /* Small text */<br>  --font-size-md: 16px;   /* Default text */<br>  --font-size-lg: 18px;   /* Large text */<br>  --font-size-xl: 24px;   /* Heading text */<br>  <br>  /* <br>    Border radius (corner roundness)<br>  */<br>  --radius-sm: 4px;   /* Slightly rounded corners */<br>  --radius-md: 8px;   /* Medium rounded corners */<br>  --radius-lg: 12px;  /* Very rounded corners */<br>  <br>  /* <br>    Shadow definitions<br>    - Used to create depth<br>  */<br>  --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);        /* Shallow shadow */<br>  --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);         /* Medium shadow */<br>  --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);       /* Deep shadow */<br>}</pre><p><strong>Why use CSS variables?</strong><br>Initially, I thought I could just write color codes directly. But with CSS variables, when you want to “make the blue a bit darker,” you just change the — color-primary value and it applies throughout the entire project. No need to find and change every blue color!</p><h3>7. Creating an Input Component</h3><p>Next is the Input component. It’s a crucial component for receiving user input in forms.</p><p><strong>components/Input/Input.jsx</strong></p><pre>import React from &#39;react&#39;;<br>import &#39;./Input.css&#39;;<br><br>/*<br>  Input Component<br>  <br>  Props explanation:<br>  - label: Label displayed above the input field<br>  - error: Error message (displayed in red if present)<br>  - helperText: Help text<br>  - fullWidth: If true, expands to parent element&#39;s width<br>*/<br>const Input = ({ <br>  label,<br>  error,<br>  helperText,<br>  fullWidth = false,<br>  ...rest  // type, placeholder, value, onChange, etc.<br>}) =&gt; {<br>  /*<br>    Combining className<br>    - Add &#39;input-error&#39; class if there&#39;s an error<br>    - Add &#39;input-full-width&#39; class if fullWidth is true<br>  */<br>  const inputClassName = `<br>    input<br>    ${error ? &#39;input-error&#39; : &#39;&#39;}<br>    ${fullWidth ? &#39;input-full-width&#39; : &#39;&#39;}<br>  `.trim();  // Remove leading/trailing whitespace<br>  <br>  return (<br><br>      {/* Display label if present */}<br>      {label &amp;&amp; (<br>        <br>          {label}<br>        <br>      )}<br>      <br>      {/* Actual input element */}<br><br>      <br>      {/* Display error message */}<br>      {error &amp;&amp; (<br>        <br>          {error}<br>        <br>      )}<br>      <br>      {/* Display helper text (only when there&#39;s no error) */}<br>      {!error &amp;&amp; helperText &amp;&amp; (<br>        <br>          {helperText}<br>        <br>      )}<br><br>  );<br>};<br><br>export default Input;</pre><p><strong>components/Input/Input.css</strong></p><pre>/* <br>  Wrapper containing the entire Input<br>  Automatically adds spacing when stacking multiple Inputs vertically<br>*/<br>.input-wrapper {<br>  display: flex;<br>  flex-direction: column;  /* Arrange vertically */<br>  gap: var(--spacing-xs);  /* Spacing between elements */<br>  margin-bottom: var(--spacing-md);  /* Bottom margin */<br>}<br><br>/* Label style */<br>.input-label {<br>  font-size: var(--font-size-sm);<br>  font-weight: 500;<br>  color: var(--color-text);<br>}<br><br>/* Base Input style */<br>.input {<br>  padding: var(--spacing-sm) var(--spacing-md);<br>  <br>  font-size: var(--font-size-md);<br>  color: var(--color-text);<br>  <br>  /* Border */<br>  border: 2px solid var(--color-border);<br>  border-radius: var(--radius-md);<br>  <br>  /* Background color */<br>  background-color: var(--color-background);<br>  <br>  /* Smooth transition effect */<br>  transition: all 0.2s ease;<br>}<br><br>/* When Input is focused (clickable for input) */<br>.input:focus {<br>  /* Remove default outline and apply custom style */<br>  outline: none;<br>  border-color: var(--color-primary);<br>  <br>  /* Blue shadow effect - clearly shows focus state */<br>  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);<br>}<br><br>/* When hovering over Input */<br>.input:hover:not(:disabled) {<br>  border-color: var(--color-primary);<br>}<br><br>/* When Input is disabled */<br>.input:disabled {<br>  background-color: #F3F4F6;  /* Gray background */<br>  cursor: not-allowed;<br>  opacity: 0.6;<br>}<br><br>/* Input in error state */<br>.input-error {<br>  border-color: var(--color-error);<br>}<br><br>.input-error:focus {<br>  /* Red shadow in error state */<br>  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);<br>}<br><br>/* Expand to full width */<br>.input-full-width {<br>  width: 100%;<br>}<br><br>/* Error message text */<br>.input-error-text {<br>  font-size: var(--font-size-sm);<br>  color: var(--color-error);<br>}<br><br>/* Helper text */<br>.input-helper-text {<br>  font-size: var(--font-size-sm);<br>  color: var(--color-text-light);<br>}</pre><p><strong>Usage Example</strong></p><pre>import React, { useState } from &#39;react&#39;;<br>import Input from &#39;./components/Input&#39;;<br><br>function LoginForm() {<br>  const [email, setEmail] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [emailError, setEmailError] = useState(&#39;&#39;);<br>  <br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    <br>    // Simple email validation<br>    if (!email.includes(&#39;@&#39;)) {<br>      setEmailError(&#39;Please enter a valid email address&#39;);<br>      return;<br>    }<br>    <br>    // Handle login...<br>  };<br>  <br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      {/* Input with label and helper text */}<br>      &lt;Input<br>        label=&quot;Email&quot;<br>        type=&quot;email&quot;<br>        placeholder=&quot;example@email.com&quot;<br>        value={email}<br>        onChange={(e) =&gt; {<br>          setEmail(e.target.value);<br>          setEmailError(&#39;&#39;);  // Clear error on input<br>        }}<br>        error={emailError}<br>        helperText=&quot;Enter the email you&#39;ll use for login&quot;<br>        fullWidth<br>      /&gt;<br>      <br>      {/* Password Input */}<br>      &lt;Input<br>        label=&quot;Password&quot;<br>        type=&quot;password&quot;<br>        placeholder=&quot;••••••••&quot;<br>        value={password}<br>        onChange={(e) =&gt; setPassword(e.target.value)}<br>        fullWidth<br>      /&gt;<br>      <br>      &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><h3>8. Building a Card Component</h3><p>Card is a component that displays content in a clean, separated way. It can be used in many places like blog post lists, product cards, etc.</p><p><strong>components/Card/Card.jsx</strong></p><pre>import React from &#39;react&#39;;<br>import &#39;./Card.css&#39;;<br><br>/*<br>  Card Component<br>  <br>  Props explanation:<br>  - children: Content inside the card<br>  - title: Card title<br>  - footer: Content displayed at the bottom of the card<br>  - hoverable: If true, apply hover effects<br>  - onClick: Function to execute when card is clicked<br>*/<br>const Card = ({ <br>  children,<br>  title,<br>  footer,<br>  hoverable = false,<br>  onClick,<br>  ...rest<br>}) =&gt; {<br>  /*<br>    Combining className<br>    - Add &#39;card-hoverable&#39; class if hoverable is true<br>    - Add &#39;card-clickable&#39; class if onClick exists (changes cursor)<br>  */<br>  const className = `<br>    card<br>    ${hoverable ? &#39;card-hoverable&#39; : &#39;&#39;}<br>    ${onClick ? &#39;card-clickable&#39; : &#39;&#39;}<br>  `.trim();<br>  <br>  return (<br><br>      {/* Display card header if title exists */}<br>      {title &amp;&amp; (<br><br>          <br>{title}<br><br>        <br><br>      )}<br>      <br>      {/* Card body content */}<br><br>        {children}<br><br>      <br>      {/* Display card footer if footer exists */}<br>      {footer &amp;&amp; (<br><br>          {footer}<br><br>      )}<br><br>  );<br>};<br><br>export default Card;</pre><p><strong>components/Card/Card.css</strong></p><pre>/* Base Card style */<br>.card {<br>  /* Background and border */<br>  background-color: var(--color-background);<br>  border: 1px solid var(--color-border);<br>  border-radius: var(--radius-lg);<br>  <br>  /* Shadow creates floating effect */<br>  box-shadow: var(--shadow-sm);<br>  <br>  /* Internal padding */<br>  padding: var(--spacing-lg);<br>  <br>  /* Smooth transition effect */<br>  transition: all 0.3s ease;<br>}<br><br>/* Card with hover effect */<br>.card-hoverable:hover {<br>  /* Lifts higher on hover */<br>  transform: translateY(-4px);<br>  box-shadow: var(--shadow-lg);<br>}<br><br>/* Clickable Card */<br>.card-clickable {<br>  cursor: pointer;<br>}<br><br>/* Card header (title area) */<br>.card-header {<br>  /* Divider line at bottom */<br>  border-bottom: 1px solid var(--color-border);<br>  padding-bottom: var(--spacing-md);<br>  margin-bottom: var(--spacing-md);<br>}<br><br>/* Card title */<br>.card-title {<br>  margin: 0;  /* Remove default margin */<br>  font-size: var(--font-size-lg);<br>  font-weight: 600;<br>  color: var(--color-text);<br>}<br><br>/* Card body */<br>.card-body {<br>  color: var(--color-text);<br>  line-height: 1.6;  /* Wider line spacing for easier reading */<br>}<br><br>/* Card footer (bottom area) */<br>.card-footer {<br>  /* Divider line at top */<br>  border-top: 1px solid var(--color-border);<br>  padding-top: var(--spacing-md);<br>  margin-top: var(--spacing-md);<br>  <br>  /* Footer text slightly lighter */<br>  color: var(--color-text-light);<br>  font-size: var(--font-size-sm);<br>}</pre><p><strong>Usage Example</strong></p><pre>import React from &#39;react&#39;;<br>import Card from &#39;./components/Card&#39;;<br>import Button from &#39;./components/Button&#39;;<br><br>function ProductList() {<br>  const products = [<br>    { id: 1, name: &#39;Product 1&#39;, price: &#39;$29&#39;, description: &#39;Amazing product&#39; },<br>    { id: 2, name: &#39;Product 2&#39;, price: &#39;$39&#39;, description: &#39;Even better product&#39; },<br>  ];<br>  <br>  return (<br>    &lt;div style={{ display: &#39;grid&#39;, gridTemplateColumns: &#39;repeat(3, 1fr)&#39;, gap: &#39;20px&#39; }}&gt;<br>      {products.map(product =&gt; (<br>        &lt;Card<br>          key={product.id}<br>          title={product.name}<br>          hoverable<br>          footer={<br>            &lt;div style={{ display: &#39;flex&#39;, justifyContent: &#39;space-between&#39;, alignItems: &#39;center&#39; }}&gt;<br>              &lt;span style={{ fontWeight: &#39;bold&#39;, fontSize: &#39;18px&#39; }}&gt;{product.price}&lt;/span&gt;<br>              &lt;Button size=&quot;sm&quot;&gt;Add to Cart&lt;/Button&gt;<br>            &lt;/div&gt;<br>          }<br>        &gt;<br>          &lt;p&gt;{product.description}&lt;/p&gt;<br>        &lt;/Card&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>9. Documenting Components</h3><p>Once you’ve created components, it’s important to write documentation on how to use them. It’s a huge help when you revisit them later or when others use them.</p><p>You can simply create README.md files to organize usage instructions for each component:</p><p><strong>components/Button/README.md</strong></p><pre># Button Component<br><br>## Description<br>A clickable button component.<br><br>## Usage<br>```jsx<br>import Button from &#39;./components/Button&#39;;<br><br>&lt;Button onClick={handleClick}&gt;Click Me&lt;/Button&gt;<br>```<br><br>## Props<br><br>**children** (ReactNode)<br>- Content to display in button<br><br>**variant** (&#39;primary&#39; | &#39;secondary&#39; | &#39;outline&#39;)<br>- Default: &#39;primary&#39;<br>- Button style type<br><br>**size** (&#39;sm&#39; | &#39;md&#39; | &#39;lg&#39;)<br>- Default: &#39;md&#39;<br>- Button size<br><br>**disabled** (boolean)<br>- Default: false<br>- Whether button is disabled<br><br>**onClick** (function)<br>- Click event handler<br><br>## Examples<br><br>### Primary Button<br>```jsx<br>&lt;Button variant=&quot;primary&quot;&gt;Save&lt;/Button&gt;<br>```<br><br>### Secondary Button<br>```jsx<br>&lt;Button variant=&quot;secondary&quot;&gt;Cancel&lt;/Button&gt;<br>```<br><br>### Large Button<br>```jsx<br>&lt;Button size=&quot;lg&quot;&gt;Sign Up&lt;/Button&gt;<br>```</pre><h3>10. Using in Real Projects</h3><p>Now let’s use our created components in an actual project. I’ll create a simple signup form.</p><p><strong>Example: Signup Form</strong></p><pre>import React, { useState } from &#39;react&#39;;<br>import Button from &#39;./components/Button&#39;;<br>import Input from &#39;./components/Input&#39;;<br>import Card from &#39;./components/Card&#39;;<br><br>function SignupForm() {<br>  // Form data state management<br>  const [formData, setFormData] = useState({<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    password: &#39;&#39;,<br>    confirmPassword: &#39;&#39;<br>  });<br>  <br>  // Error state management<br>  const [errors, setErrors] = useState({});<br>  <br>  // Handle Input value changes<br>  const handleChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setFormData(prev =&gt; ({<br>      ...prev,<br>      [name]: value<br>    }));<br>    <br>    // Clear error for that field when inputting<br>    if (errors[name]) {<br>      setErrors(prev =&gt; ({<br>        ...prev,<br>        [name]: &#39;&#39;<br>      }));<br>    }<br>  };<br>  <br>  // Form validation<br>  const validateForm = () =&gt; {<br>    const newErrors = {};<br>    <br>    if (!formData.name) {<br>      newErrors.name = &#39;Please enter your name&#39;;<br>    }<br>    <br>    if (!formData.email) {<br>      newErrors.email = &#39;Please enter your email&#39;;<br>    } else if (!formData.email.includes(&#39;@&#39;)) {<br>      newErrors.email = &#39;Invalid email format&#39;;<br>    }<br>    <br>    if (!formData.password) {<br>      newErrors.password = &#39;Please enter your password&#39;;<br>    } else if (formData.password.length &lt; 8) {<br>      newErrors.password = &#39;Password must be at least 8 characters&#39;;<br>    }<br>    <br>    if (formData.password !== formData.confirmPassword) {<br>      newErrors.confirmPassword = &#39;Passwords do not match&#39;;<br>    }<br>    <br>    return newErrors;<br>  };<br>  <br>  // Handle form submission<br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    <br>    const newErrors = validateForm();<br>    <br>    if (Object.keys(newErrors).length &gt; 0) {<br>      // If there are errors, update error state<br>      setErrors(newErrors);<br>      return;<br>    }<br>    <br>    // If no errors, handle signup<br>    console.log(&#39;Signup data:&#39;, formData);<br>    alert(&#39;Signup successful!&#39;);<br>  };<br>  <br>  return (<br>    &lt;div style={{ <br>      maxWidth: &#39;500px&#39;, <br>      margin: &#39;50px auto&#39;,<br>      padding: &#39;20px&#39;<br>    }}&gt;<br>      {/* Wrap form in Card component for clean presentation */}<br>      &lt;Card title=&quot;Sign Up&quot;&gt;<br>        &lt;form onSubmit={handleSubmit}&gt;<br>          {/* Name input */}<br>          &lt;Input<br>            label=&quot;Name&quot;<br>            name=&quot;name&quot;<br>            type=&quot;text&quot;<br>            placeholder=&quot;John Doe&quot;<br>            value={formData.name}<br>            onChange={handleChange}<br>            error={errors.name}<br>            fullWidth<br>          /&gt;<br>          <br>          {/* Email input */}<br>          &lt;Input<br>            label=&quot;Email&quot;<br>            name=&quot;email&quot;<br>            type=&quot;email&quot;<br>            placeholder=&quot;example@email.com&quot;<br>            value={formData.email}<br>            onChange={handleChange}<br>            error={errors.email}<br>            helperText=&quot;Enter the email you&#39;ll use for login&quot;<br>            fullWidth<br>          /&gt;<br>          <br>          {/* Password input */}<br>          &lt;Input<br>            label=&quot;Password&quot;<br>            name=&quot;password&quot;<br>            type=&quot;password&quot;<br>            placeholder=&quot;••••••••&quot;<br>            value={formData.password}<br>            onChange={handleChange}<br>            error={errors.password}<br>            helperText=&quot;Must be at least 8 characters&quot;<br>            fullWidth<br>          /&gt;<br>          <br>          {/* Password confirmation */}<br>          &lt;Input<br>            label=&quot;Confirm Password&quot;<br>            name=&quot;confirmPassword&quot;<br>            type=&quot;password&quot;<br>            placeholder=&quot;••••••••&quot;<br>            value={formData.confirmPassword}<br>            onChange={handleChange}<br>            error={errors.confirmPassword}<br>            fullWidth<br>          /&gt;<br>          <br>          {/* Button group */}<br>          &lt;div style={{ <br>            display: &#39;flex&#39;, <br>            gap: &#39;10px&#39;, <br>            marginTop: &#39;20px&#39; <br>          }}&gt;<br>            &lt;Button <br>              type=&quot;submit&quot; <br>              size=&quot;lg&quot;<br>              style={{ flex: 1 }}  {/* Button fills horizontally */}<br>            &gt;<br>              Sign Up<br>            &lt;/Button&gt;<br>            <br>            &lt;Button <br>              type=&quot;button&quot;<br>              variant=&quot;outline&quot; <br>              size=&quot;lg&quot;<br>              onClick={() =&gt; {<br>                // Reset form<br>                setFormData({<br>                  name: &#39;&#39;,<br>                  email: &#39;&#39;,<br>                  password: &#39;&#39;,<br>                  confirmPassword: &#39;&#39;<br>                });<br>                setErrors({});<br>              }}<br>            &gt;<br>              Reset<br>            &lt;/Button&gt;<br>          &lt;/div&gt;<br>        &lt;/form&gt;<br>      &lt;/Card&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default SignupForm;</pre><p><strong>Key points in this code:</strong></p><p><strong>Reusability</strong>: Combined Button, Input, and Card components to create a complex form.</p><p><strong>Consistency</strong>: All components use the same design tokens, creating unity.</p><p><strong>Maintainability</strong>: If you want to change Input styles later, just modify Input.css.</p><p><strong>Development Speed</strong>: Could quickly develop the form without worrying about styles.</p><h3>11. Conclusion</h3><p>Through studying design systems, one learns that while you might initially think “is this really necessary?”, once you build it, development becomes so much easier.</p><p>Especially when creating new pages, you can focus on development immediately without worrying about “what button style should I use?” or “how much spacing should I add?”. And when you want to change the design later, you just modify the token values and it applies throughout the entire project, which is really convenient.</p><p>It’s recommended to create a basic design system first when starting a new project. Start by making just Button, Input, and Card, then add more as needed.</p><p>You should also start with a small component library. It doesn’t need to be perfect. Just improve and add to it gradually as you work on projects. The important thing is “getting started”!</p><p>I hope this article helps those who wanted to create their own design system. 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99fd70a4d6be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React and TypeScript: Type-Safe Component Design Patterns]]></title>
            <link>https://medium.com/@dlrnjstjs/react-and-typescript-type-safe-component-design-patterns-4c5c1d7bf334?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c5c1d7bf334</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 16:23:34 GMT</pubDate>
            <atom:updated>2025-10-29T16:23:34.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Why Use TypeScript with React?</h3><p>Using TypeScript with React projects allows errors to be caught during development. The IDE immediately alerts when incorrect props are passed to components or when attempting to access non-existent properties.</p><p><strong>Comparison between JavaScript and TypeScript:</strong></p><ul><li><strong>Type Checking Time:</strong> JavaScript checks at runtime (after errors occur), while TypeScript checks at compile time (during code writing)</li><li><strong>IDE Support:</strong> JavaScript has limited support, while TypeScript provides autocomplete and type hints</li><li><strong>Refactoring:</strong> JavaScript requires manual verification everywhere, while TypeScript automatically validates through the type system</li><li><strong>Code Documentation:</strong> JavaScript requires separate comments, while types themselves serve as documentation</li></ul><h3>2. Basic Props Type Definition</h3><p>Starting with the most basic component, first define what props will be received when creating a Button component.</p><pre>// First define the type of Props<br>interface ButtonProps {<br>  text: string;      // Text to display on the button<br>  color: string;     // Button color<br>  disabled: boolean; // Whether it&#39;s disabled<br>}<br><br>// Specify the Props type for the function component<br>function Button({ text, color, disabled }: ButtonProps) {<br>  return (<br>    &lt;button <br>      style={{ backgroundColor: color }}<br>      disabled={disabled}<br>    &gt;<br>      {text}<br>    &lt;/button&gt;<br>  );<br>}<br><br>// Usage example<br>function App() {<br>  // ✅ Correct usage<br>  return &lt;Button text=&quot;Click&quot; color=&quot;blue&quot; disabled={false} /&gt;;<br>  <br>  // ❌ TypeScript will throw errors<br>  // return &lt;Button text=&quot;Click&quot; /&gt;; // Error: missing color and disabled<br>  // return &lt;Button text={123} color=&quot;blue&quot; disabled={false} /&gt;; // Error: text is a number<br>}</pre><p><strong>Key Points:</strong></p><ul><li>Use interface to define the structure of props</li><li>Clearly specify the name and type of each property</li><li>Applying types to component parameters prevents passing incorrect props</li></ul><h3>3. Optional Props and Default Values</h3><p>Not all props need to be required. Optional props are marked with ?.</p><pre>interface ButtonProps {<br>  text: string;<br>  color?: string;     // Mark with ? to indicate optional props<br>  disabled?: boolean;<br>  onClick?: () =&gt; void; // Functions can also be optional<br>}<br><br>// Method 1: Set default values in function parameters<br>function Button({ <br>  text, <br>  color = &#39;blue&#39;,      // Use &#39;blue&#39; if color is not provided<br>  disabled = false,    // Use false if disabled is not provided<br>  onClick <br>}: ButtonProps) {<br>  return (<br>    &lt;button <br>      style={{ backgroundColor: color }}<br>      disabled={disabled}<br>      onClick={onClick}<br>    &gt;<br>      {text}<br>    &lt;/button&gt;<br>  );<br>}<br><br>// Method 2: Using defaultProps (more common in React 18 and below)<br>Button.defaultProps = {<br>  color: &#39;blue&#39;,<br>  disabled: false,<br>};<br><br>// Usage example<br>function App() {<br>  // ✅ Can omit color and disabled<br>  return &lt;Button text=&quot;Click&quot; /&gt;;<br>  <br>  // ✅ Can pass only what you want<br>  return &lt;Button text=&quot;Click&quot; color=&quot;red&quot; /&gt;;<br>}</pre><p><strong>Key Points:</strong></p><ul><li>Adding ? means no error occurs even if that prop is not passed</li><li>Default values can be set using = in destructuring assignment</li><li>Function types are defined as () =&gt; void (function with no parameters and no return value)</li></ul><h3>4. Defining Children Types</h3><p>Content between components (children) can also have types specified.</p><pre>import { ReactNode } from &#39;react&#39;;<br><br>// ReactNode means anything that React can render<br>// (strings, numbers, JSX elements, null, undefined, etc.)<br>interface CardProps {<br>  title: string;<br>  children: ReactNode; // Explicitly define the type of children<br>}<br><br>function Card({ title, children }: CardProps) {<br>  return (<br>    &lt;div className=&quot;card&quot;&gt;<br>      &lt;h2&gt;{title}&lt;/h2&gt;<br>      &lt;div className=&quot;card-content&quot;&gt;<br>        {children}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Usage example<br>function App() {<br>  return (<br>    &lt;Card title=&quot;My Card&quot;&gt;<br>      &lt;p&gt;Any content can go here&lt;/p&gt;<br>      &lt;button&gt;Buttons work too&lt;/button&gt;<br>      &lt;div&gt;Other components as well&lt;/div&gt;<br>    &lt;/Card&gt;<br>  );<br>}</pre><p><strong>Various Children Types:</strong></p><pre>import { ReactNode, ReactElement } from &#39;react&#39;;<br><br>interface ExampleProps {<br>  // 1. ReactNode - Widest range (recommended)<br>  children: ReactNode; <br>  <br>  // 2. ReactElement - Only allows JSX elements (no strings or numbers)<br>  element: ReactElement;<br>  <br>  // 3. Only allows strings<br>  text: string;<br>  <br>  // 4. Only allows specific components<br>  button: ReactElement&lt;ButtonProps&gt;;<br>  <br>  // 5. Only allows multiple specific elements<br>  items: ReactElement[];<br>}</pre><p><strong>Key Points:</strong></p><ul><li>ReactNode is the most flexible children type</li><li>ReactElement only allows actual JSX elements</li><li>Generics can be used for more specific types</li></ul><h3>5. Event Handler Types</h3><p>React events are slightly different from browser’s native events. React uses Synthetic Events.</p><pre>import { ChangeEvent, MouseEvent, FormEvent } from &#39;react&#39;;<br><br>interface FormProps {<br>  onSubmit: (data: string) =&gt; void; // Custom callback function<br>}<br><br>function Form({ onSubmit }: FormProps) {<br>  // Type for input&#39;s change event<br>  // ChangeEvent&lt;HTMLInputElement&gt;: change event from input element<br>  const handleInputChange = (e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    console.log(e.target.value); // Current value of input<br>  };<br><br>  // Type for button&#39;s click event<br>  // MouseEvent&lt;HTMLButtonElement&gt;: mouse event from button element<br>  const handleButtonClick = (e: MouseEvent&lt;HTMLButtonElement&gt;) =&gt; {<br>    console.log(&#39;Button clicked&#39;);<br>    e.preventDefault(); // Prevent default behavior<br>  };<br><br>  // Type for form&#39;s submit event<br>  // FormEvent&lt;HTMLFormElement&gt;: submit event from form element<br>  const handleSubmit = (e: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault(); // Prevent page reload<br>    const formData = new FormData(e.currentTarget);<br>    const value = formData.get(&#39;username&#39;) as string;<br>    onSubmit(value); // Pass data to parent component<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input <br>        name=&quot;username&quot;<br>        onChange={handleInputChange} <br>      /&gt;<br>      &lt;button onClick={handleButtonClick}&gt;<br>        Submit<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p><strong>Common Event Types:</strong></p><p><strong>Click events:</strong> Use MouseEvent&lt;HTMLButtonElement&gt; for buttons and div clicks</p><p><strong>Input change:</strong> Use ChangeEvent&lt;HTMLInputElement&gt; for input and textarea value changes</p><p><strong>Form submit:</strong> Use FormEvent&lt;HTMLFormElement&gt; for form submissions</p><p><strong>Keyboard events:</strong> Use KeyboardEvent&lt;HTMLInputElement&gt; for key input detection</p><p><strong>Focus events:</strong> Use FocusEvent&lt;HTMLInputElement&gt; for focus in/out events</p><p><strong>Key Points:</strong></p><ul><li>React events are imported from the react package</li><li>Event types follow the format EventType&lt;HTMLElementType&gt;</li><li>e.target accesses the element where the event occurred</li><li>e.currentTarget points to the element where the event handler is attached</li></ul><h3>6. Creating Generic Components</h3><p>Using generics allows creating reusable components that can handle various types of data.</p><pre>// T is short for &quot;Type&quot; - a generic variable that can be any type<br>interface ListProps&lt;T&gt; {<br>  items: T[];                    // Array of type T<br>  renderItem: (item: T) =&gt; ReactNode; // Function that receives T type item and renders it<br>}<br><br>// Add &lt;T&gt; to indicate it&#39;s a generic component<br>function List&lt;T&gt;({ items, renderItem }: ListProps&lt;T&gt;) {<br>  return (<br>    &lt;ul&gt;<br>      {items.map((item, index) =&gt; (<br>        &lt;li key={index}&gt;<br>          {renderItem(item)}<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>// Usage example 1: String array<br>function App1() {<br>  const fruits = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;];<br>  <br>  return (<br>    &lt;List <br>      items={fruits}<br>      renderItem={(fruit) =&gt; &lt;span&gt;{fruit}&lt;/span&gt;}<br>      // fruit is automatically inferred as string type<br>    /&gt;<br>  );<br>}<br><br>// Usage example 2: Object array<br>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br><br>function App2() {<br>  const users: User[] = [<br>    { id: 1, name: &#39;John Doe&#39;, email: &#39;john@example.com&#39; },<br>    { id: 2, name: &#39;Jane Smith&#39;, email: &#39;jane@example.com&#39; },<br>  ];<br>  <br>  return (<br>    &lt;List <br>      items={users}<br>      renderItem={(user) =&gt; (<br>        // user is automatically inferred as User type<br>        &lt;div&gt;<br>          &lt;strong&gt;{user.name}&lt;/strong&gt;<br>          &lt;span&gt;{user.email}&lt;/span&gt;<br>        &lt;/div&gt;<br>      )}<br>    /&gt;<br>  );<br>}</pre><p><strong>A More Complex Example: Select Component</strong></p><pre>// T is the option&#39;s value type, K is the key name for the label to display<br>interface SelectProps&lt;T, K extends keyof T&gt; {<br>  options: T[];           // Available options<br>  value: T[K];           // Currently selected value<br>  onChange: (value: T[K]) =&gt; void; // Function to call when value changes<br>  labelKey: K;           // Name of property to display on screen<br>  valueKey: K;           // Name of property to use as actual value<br>}<br><br>function Select&lt;T, K extends keyof T&gt;({ <br>  options, <br>  value, <br>  onChange, <br>  labelKey, <br>  valueKey <br>}: SelectProps&lt;T, K&gt;) {<br>  return (<br>    &lt;select <br>      value={String(value)}<br>      onChange={(e) =&gt; {<br>        const selectedOption = options.find(<br>          option =&gt; String(option[valueKey]) === e.target.value<br>        );<br>        if (selectedOption) {<br>          onChange(selectedOption[valueKey]);<br>        }<br>      }}<br>    &gt;<br>      {options.map((option, index) =&gt; (<br>        &lt;option key={index} value={String(option[valueKey])}&gt;<br>          {String(option[labelKey])}<br>        &lt;/option&gt;<br>      ))}<br>    &lt;/select&gt;<br>  );<br>}<br><br>// Usage example<br>interface Country {<br>  code: string;<br>  name: string;<br>  population: number;<br>}<br><br>function App() {<br>  const countries: Country[] = [<br>    { code: &#39;KR&#39;, name: &#39;South Korea&#39;, population: 51000000 },<br>    { code: &#39;US&#39;, name: &#39;United States&#39;, population: 331000000 },<br>    { code: &#39;JP&#39;, name: &#39;Japan&#39;, population: 126000000 },<br>  ];<br>  <br>  const [selected, setSelected] = useState&lt;string&gt;(&#39;KR&#39;);<br>  <br>  return (<br>    &lt;Select<br>      options={countries}<br>      value={selected}<br>      onChange={setSelected}<br>      labelKey=&quot;name&quot;      // Display name on screen<br>      valueKey=&quot;code&quot;      // Use code as actual value<br>      // TypeScript checks if labelKey and valueKey are properties of Country<br>    /&gt;<br>  );<br>}</pre><p><strong>Key Points:</strong></p><ul><li>Using generic &lt;T&gt; allows one component to handle multiple types of data</li><li>keyof T gets all keys of type T as a union type</li><li>extends can be used to add constraints to generic types</li><li>TypeScript automatically infers types at usage time</li></ul><h3>7. Handling Conditional Props with Discriminated Unions</h3><p>Sometimes different props are needed depending on the value of a specific prop. This is when Discriminated Unions are used.</p><pre>// Define multiple types distinguished by the &quot;type&quot; property<br>// variant serves as the &quot;discriminant&quot; role<br><br>// When button variant is &#39;primary&#39;<br>type PrimaryButtonProps = {<br>  variant: &#39;primary&#39;;<br>  text: string;<br>  onClick: () =&gt; void;<br>  // primary button doesn&#39;t need an icon<br>};<br><br>// When button variant is &#39;icon&#39;<br>type IconButtonProps = {<br>  variant: &#39;icon&#39;;<br>  icon: ReactNode;       // icon is required<br>  onClick: () =&gt; void;<br>  text?: never;          // text must not exist<br>};<br><br>// When button variant is &#39;link&#39;<br>type LinkButtonProps = {<br>  variant: &#39;link&#39;;<br>  text: string;<br>  href: string;          // link requires href<br>  onClick?: never;       // onClick must not exist<br>};<br><br>// Can be one of three types<br>type ButtonProps = PrimaryButtonProps | IconButtonProps | LinkButtonProps;<br><br>function Button(props: ButtonProps) {<br>  // TypeScript automatically narrows available props based on variant value<br>  <br>  if (props.variant === &#39;primary&#39;) {<br>    // In this block, props is PrimaryButtonProps type<br>    return (<br>      &lt;button onClick={props.onClick}&gt;<br>        {props.text}<br>      &lt;/button&gt;<br>    );<br>  }<br>  <br>  if (props.variant === &#39;icon&#39;) {<br>    // In this block, props is IconButtonProps type<br>    return (<br>      &lt;button onClick={props.onClick}&gt;<br>        {props.icon}<br>      &lt;/button&gt;<br>    );<br>  }<br>  <br>  // At this point, props is automatically LinkButtonProps type<br>  return (<br>    &lt;a href={props.href}&gt;<br>      {props.text}<br>    &lt;/a&gt;<br>  );<br>}<br><br>// Usage examples<br>function App() {<br>  return (<br>    &lt;&gt;<br>      {/* ✅ Correct usage */}<br>      &lt;Button variant=&quot;primary&quot; text=&quot;Click&quot; onClick={() =&gt; {}} /&gt;<br>      &lt;Button variant=&quot;icon&quot; icon={&lt;span&gt;🔍&lt;/span&gt;} onClick={() =&gt; {}} /&gt;<br>      &lt;Button variant=&quot;link&quot; text=&quot;Link&quot; href=&quot;/home&quot; /&gt;<br>      <br>      {/* ❌ TypeScript will throw errors */}<br>      {/* &lt;Button variant=&quot;primary&quot; icon={&lt;span&gt;🔍&lt;/span&gt;} onClick={() =&gt; {}} /&gt; */}<br>      {/* primary doesn&#39;t have icon */}<br>      <br>      {/* &lt;Button variant=&quot;link&quot; text=&quot;Link&quot; href=&quot;/home&quot; onClick={() =&gt; {}} /&gt; */}<br>      {/* link doesn&#39;t have onClick */}<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>More Complex Example: Alert Component</strong></p><pre>// Common properties<br>type BaseAlertProps = {<br>  message: string;<br>  onClose?: () =&gt; void;<br>};<br><br>// success type<br>type SuccessAlertProps = BaseAlertProps &amp; {<br>  type: &#39;success&#39;;<br>  showIcon?: boolean;     // success can optionally display icon<br>};<br><br>// error type<br>type ErrorAlertProps = BaseAlertProps &amp; {<br>  type: &#39;error&#39;;<br>  errorCode: string;      // error requires error code<br>  retry?: () =&gt; void;     // retry function is optional<br>};<br><br>// warning type<br>type WarningAlertProps = BaseAlertProps &amp; {<br>  type: &#39;warning&#39;;<br>  dismissible: boolean;   // warning requires dismissible property<br>};<br><br>type AlertProps = SuccessAlertProps | ErrorAlertProps | WarningAlertProps;<br><br>function Alert(props: AlertProps) {<br>  const baseStyles = &#39;p-4 rounded mb-2&#39;;<br>  <br>  // Render different styles and content based on type<br>  switch (props.type) {<br>    case &#39;success&#39;:<br>      return (<br>        &lt;div className={`${baseStyles} bg-green-100`}&gt;<br>          {props.showIcon &amp;&amp; &lt;span&gt;✓&lt;/span&gt;}<br>          {props.message}<br>          {props.onClose &amp;&amp; &lt;button onClick={props.onClose}&gt;×&lt;/button&gt;}<br>        &lt;/div&gt;<br>      );<br>      <br>    case &#39;error&#39;:<br>      return (<br>        &lt;div className={`${baseStyles} bg-red-100`}&gt;<br>          &lt;strong&gt;Error {props.errorCode}&lt;/strong&gt;<br>          &lt;p&gt;{props.message}&lt;/p&gt;<br>          {props.retry &amp;&amp; &lt;button onClick={props.retry}&gt;Retry&lt;/button&gt;}<br>          {props.onClose &amp;&amp; &lt;button onClick={props.onClose}&gt;×&lt;/button&gt;}<br>        &lt;/div&gt;<br>      );<br>      <br>    case &#39;warning&#39;:<br>      return (<br>        &lt;div className={`${baseStyles} bg-yellow-100`}&gt;<br>          {props.message}<br>          {props.dismissible &amp;&amp; props.onClose &amp;&amp; (<br>            &lt;button onClick={props.onClose}&gt;×&lt;/button&gt;<br>          )}<br>        &lt;/div&gt;<br>      );<br>  }<br>}</pre><p><strong>Key Points:</strong></p><ul><li>Discriminated Union uses one common property (discriminant) to distinguish types</li><li>never type can be used to explicitly state that certain props must not exist</li><li>TypeScript automatically narrows types within conditionals (Type Narrowing)</li><li>If there are common properties between types, they can be combined with &amp; (intersection)</li></ul><h3>8. Type Safety in Custom Hooks</h3><p>Custom Hooks are also easy to use and safe when types are clearly defined.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>// Explicitly define the return type of the Hook<br>interface UseToggleReturn {<br>  isOn: boolean;<br>  toggle: () =&gt; void;<br>  setOn: () =&gt; void;<br>  setOff: () =&gt; void;<br>}<br><br>// Simple toggle hook<br>function useToggle(initialValue: boolean = false): UseToggleReturn {<br>  const [isOn, setIsOn] = useState(initialValue);<br>  <br>  const toggle = () =&gt; setIsOn(prev =&gt; !prev);<br>  const setOn = () =&gt; setIsOn(true);<br>  const setOff = () =&gt; setIsOn(false);<br>  <br>  // Return type must match UseToggleReturn<br>  return { isOn, toggle, setOn, setOff };<br>}<br><br>// Usage example<br>function Modal() {<br>  const { isOn: isOpen, toggle, setOff } = useToggle(false);<br>  <br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={toggle}&gt;Open Modal&lt;/button&gt;<br>      {isOpen &amp;&amp; (<br>        &lt;div className=&quot;modal&quot;&gt;<br>          &lt;p&gt;Modal content&lt;/p&gt;<br>          &lt;button onClick={setOff}&gt;Close&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>Custom Hook Using Generics</strong></p><pre>// Hook for managing API call state<br>interface UseFetchState&lt;T&gt; {<br>  data: T | null;      // Response data<br>  loading: boolean;    // Whether loading<br>  error: Error | null; // Error object<br>}<br><br>interface UseFetchReturn&lt;T&gt; extends UseFetchState&lt;T&gt; {<br>  refetch: () =&gt; void; // Function to request again<br>}<br><br>// T is the type of API response data<br>function useFetch&lt;T&gt;(url: string): UseFetchReturn&lt;T&gt; {<br>  const [state, setState] = useState&lt;UseFetchState&lt;T&gt;&gt;({<br>    data: null,<br>    loading: true,<br>    error: null,<br>  });<br>  <br>  const fetchData = async () =&gt; {<br>    setState(prev =&gt; ({ ...prev, loading: true }));<br>    <br>    try {<br>      const response = await fetch(url);<br>      const json = await response.json() as T; // Convert response to T type<br>      <br>      setState({<br>        data: json,<br>        loading: false,<br>        error: null,<br>      });<br>    } catch (error) {<br>      setState({<br>        data: null,<br>        loading: false,<br>        error: error as Error, // Assert error as Error type<br>      });<br>    }<br>  };<br>  <br>  useEffect(() =&gt; {<br>    fetchData();<br>  }, [url]);<br>  <br>  return {<br>    ...state,<br>    refetch: fetchData,<br>  };<br>}<br><br>// Usage example<br>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br><br>function UserProfile() {<br>  // When specifying User type, data becomes User | null type<br>  const { data, loading, error, refetch } = useFetch&lt;User&gt;(<br>    &#39;https://api.example.com/user/1&#39;<br>  );<br>  <br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br>  if (!data) return &lt;div&gt;No data&lt;/div&gt;;<br>  <br>  // At this point data is User type<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{data.name}&lt;/h2&gt;<br>      &lt;p&gt;{data.email}&lt;/p&gt;<br>      &lt;button onClick={refetch}&gt;Refresh&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Hook Returning Array (Similar to useState Pattern)</strong></p><pre>// Hook returning tuple type<br>function useCounter(initialValue: number = 0): [number, () =&gt; void, () =&gt; void] {<br>  const [count, setCount] = useState(initialValue);<br>  <br>  const increment = () =&gt; setCount(prev =&gt; prev + 1);<br>  const decrement = () =&gt; setCount(prev =&gt; prev - 1);<br>  <br>  // Returning as array allows free naming on the consumer side<br>  return [count, increment, decrement];<br>}<br><br>// Usage example<br>function Counter() {<br>  // Receive with array destructuring like useState<br>  const [count, increment, decrement] = useCounter(0);<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>Key Points:</strong></p><ul><li>Specifying custom Hook return types enables good autocomplete for consumers</li><li>Using generics allows creating Hooks that can handle multiple types of data</li><li>Returning as object allows destructuring only what’s needed regardless of order</li><li>Returning as array allows free naming on the consumer side like useState</li></ul><h3>9. Real-World Example: Type-Safe Form Component</h3><p>Let’s create a practical Form component that combines everything learned so far.</p><pre>import { useState, FormEvent, ChangeEvent } from &#39;react&#39;;<br><br>// Basic properties of form field<br>interface BaseFieldConfig {<br>  label: string;<br>  required?: boolean;<br>  placeholder?: string;<br>}<br><br>// Configuration for each field type<br>type TextFieldConfig = BaseFieldConfig &amp; {<br>  type: &#39;text&#39; | &#39;email&#39; | &#39;password&#39;;<br>  minLength?: number;<br>  maxLength?: number;<br>};<br><br>type NumberFieldConfig = BaseFieldConfig &amp; {<br>  type: &#39;number&#39;;<br>  min?: number;<br>  max?: number;<br>};<br><br>type SelectFieldConfig = BaseFieldConfig &amp; {<br>  type: &#39;select&#39;;<br>  options: Array&lt;{ value: string; label: string }&gt;;<br>};<br><br>// Union type of all field configurations<br>type FieldConfig = TextFieldConfig | NumberFieldConfig | SelectFieldConfig;<br><br>// Form configuration (key is field name, value is field configuration)<br>type FormConfig = Record&lt;string, FieldConfig&gt;;<br><br>// Form data type (all values are strings)<br>type FormData = Record&lt;string, string&gt;;<br><br>// Form component Props<br>interface FormProps&lt;T extends FormConfig&gt; {<br>  config: T;                                    // Form configuration<br>  onSubmit: (data: FormData) =&gt; void;          // Submit handler<br>  initialValues?: Partial&lt;FormData&gt;;           // Initial values (optional)<br>  submitButtonText?: string;                   // Submit button text<br>}<br><br>function Form&lt;T extends FormConfig&gt;({ <br>  config, <br>  onSubmit, <br>  initialValues = {},<br>  submitButtonText = &#39;Submit&#39;<br>}: FormProps&lt;T&gt;) {<br>  // Form data state<br>  const [formData, setFormData] = useState&lt;FormData&gt;(initialValues);<br>  <br>  // Validation error state<br>  const [errors, setErrors] = useState&lt;Record&lt;string, string&gt;&gt;({});<br>  <br>  // Field value change handler<br>  const handleChange = (name: string, value: string) =&gt; {<br>    setFormData(prev =&gt; ({ ...prev, [name]: value }));<br>    <br>    // Remove error for that field when value changes<br>    if (errors[name]) {<br>      setErrors(prev =&gt; {<br>        const newErrors = { ...prev };<br>        delete newErrors[name];<br>        return newErrors;<br>      });<br>    }<br>  };<br>  <br>  // Validation function<br>  const validate = (): boolean =&gt; {<br>    const newErrors: Record&lt;string, string&gt; = {};<br>    <br>    // Iterate through each field for validation<br>    Object.entries(config).forEach(([name, fieldConfig]) =&gt; {<br>      const value = formData[name] || &#39;&#39;;<br>      <br>      // Check required fields<br>      if (fieldConfig.required &amp;&amp; !value) {<br>        newErrors[name] = `${fieldConfig.label} is required`;<br>        return;<br>      }<br>      <br>      // Validation by field type<br>      if (fieldConfig.type === &#39;text&#39; || fieldConfig.type === &#39;email&#39; || fieldConfig.type === &#39;password&#39;) {<br>        if (fieldConfig.minLength &amp;&amp; value.length &lt; fieldConfig.minLength) {<br>          newErrors[name] = `Minimum ${fieldConfig.minLength} characters required`;<br>        }<br>        if (fieldConfig.maxLength &amp;&amp; value.length &gt; fieldConfig.maxLength) {<br>          newErrors[name] = `Maximum ${fieldConfig.maxLength} characters allowed`;<br>        }<br>      }<br>      <br>      if (fieldConfig.type === &#39;number&#39;) {<br>        const numValue = Number(value);<br>        if (isNaN(numValue)) {<br>          newErrors[name] = &#39;Please enter numbers only&#39;;<br>        } else {<br>          if (fieldConfig.min !== undefined &amp;&amp; numValue &lt; fieldConfig.min) {<br>            newErrors[name] = `Minimum value is ${fieldConfig.min}`;<br>          }<br>          if (fieldConfig.max !== undefined &amp;&amp; numValue &gt; fieldConfig.max) {<br>            newErrors[name] = `Maximum value is ${fieldConfig.max}`;<br>          }<br>        }<br>      }<br>      <br>      if (fieldConfig.type === &#39;email&#39;) {<br>        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;<br>        if (value &amp;&amp; !emailRegex.test(value)) {<br>          newErrors[name] = &#39;Invalid email format&#39;;<br>        }<br>      }<br>    });<br>    <br>    setErrors(newErrors);<br>    return Object.keys(newErrors).length === 0;<br>  };<br>  <br>  // Form submit handler<br>  const handleSubmit = (e: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br>    <br>    if (validate()) {<br>      onSubmit(formData);<br>    }<br>  };<br>  <br>  // Field rendering function<br>  const renderField = (name: string, fieldConfig: FieldConfig) =&gt; {<br>    const value = formData[name] || &#39;&#39;;<br>    const error = errors[name];<br>    <br>    return (<br>      &lt;div key={name} style={{ marginBottom: &#39;1rem&#39; }}&gt;<br>        &lt;label&gt;<br>          {fieldConfig.label}<br>          {fieldConfig.required &amp;&amp; &lt;span style={{ color: &#39;red&#39; }}&gt; *&lt;/span&gt;}<br>        &lt;/label&gt;<br>        <br>        {/* Render different input based on field type */}<br>        {fieldConfig.type === &#39;select&#39; ? (<br>          &lt;select<br>            value={value}<br>            onChange={(e: ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; <br>              handleChange(name, e.target.value)<br>            }<br>            style={{ width: &#39;100%&#39;, padding: &#39;0.5rem&#39; }}<br>          &gt;<br>            &lt;option value=&quot;&quot;&gt;Please select&lt;/option&gt;<br>            {fieldConfig.options.map(option =&gt; (<br>              &lt;option key={option.value} value={option.value}&gt;<br>                {option.label}<br>              &lt;/option&gt;<br>            ))}<br>          &lt;/select&gt;<br>        ) : (<br>          &lt;input<br>            type={fieldConfig.type}<br>            value={value}<br>            onChange={(e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; <br>              handleChange(name, e.target.value)<br>            }<br>            placeholder={fieldConfig.placeholder}<br>            style={{ width: &#39;100%&#39;, padding: &#39;0.5rem&#39; }}<br>          /&gt;<br>        )}<br>        <br>        {/* Display error message */}<br>        {error &amp;&amp; (<br>          &lt;div style={{ color: &#39;red&#39;, fontSize: &#39;0.875rem&#39;, marginTop: &#39;0.25rem&#39; }}&gt;<br>            {error}<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    );<br>  };<br>  <br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      {/* Render all fields */}<br>      {Object.entries(config).map(([name, fieldConfig]) =&gt; <br>        renderField(name, fieldConfig)<br>      )}<br>      <br>      &lt;button <br>        type=&quot;submit&quot;<br>        style={{ <br>          padding: &#39;0.5rem 1rem&#39;, <br>          backgroundColor: &#39;#007bff&#39;, <br>          color: &#39;white&#39;,<br>          border: &#39;none&#39;,<br>          borderRadius: &#39;4px&#39;,<br>          cursor: &#39;pointer&#39;<br>        }}<br>      &gt;<br>        {submitButtonText}<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}<br><br>// Usage example<br>function SignUpPage() {<br>  // Define form configuration<br>  const signUpFormConfig = {<br>    username: {<br>      type: &#39;text&#39; as const,<br>      label: &#39;Username&#39;,<br>      required: true,<br>      minLength: 3,<br>      maxLength: 20,<br>      placeholder: &#39;Enter username&#39;<br>    },<br>    email: {<br>      type: &#39;email&#39; as const,<br>      label: &#39;Email&#39;,<br>      required: true,<br>      placeholder: &#39;email@example.com&#39;<br>    },<br>    password: {<br>      type: &#39;password&#39; as const,<br>      label: &#39;Password&#39;,<br>      required: true,<br>      minLength: 8,<br>      placeholder: &#39;Enter password&#39;<br>    },<br>    age: {<br>      type: &#39;number&#39; as const,<br>      label: &#39;Age&#39;,<br>      required: false,<br>      min: 18,<br>      max: 100<br>    },<br>    country: {<br>      type: &#39;select&#39; as const,<br>      label: &#39;Country&#39;,<br>      required: true,<br>      options: [<br>        { value: &#39;us&#39;, label: &#39;United States&#39; },<br>        { value: &#39;uk&#39;, label: &#39;United Kingdom&#39; },<br>        { value: &#39;jp&#39;, label: &#39;Japan&#39; }<br>      ]<br>    }<br>  } satisfies FormConfig; // Type check with satisfies<br>  <br>  // Form submit handler<br>  const handleSubmit = (data: FormData) =&gt; {<br>    console.log(&#39;Form data:&#39;, data);<br>    // Can make API calls here<br>  };<br>  <br>  return (<br>    &lt;div style={{ maxWidth: &#39;500px&#39;, margin: &#39;0 auto&#39;, padding: &#39;2rem&#39; }}&gt;<br>      &lt;h1&gt;Sign Up&lt;/h1&gt;<br>      &lt;Form <br>        config={signUpFormConfig}<br>        onSubmit={handleSubmit}<br>        submitButtonText=&quot;Sign Up&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>TypeScript Features Used in This Example:</strong></p><p><strong>Discriminated Union:</strong> Distinguishes field types by type property (FieldConfig)</p><p><strong>Generic:</strong> Handles various form configurations (Form component)</p><p><strong>Record Type:</strong> Defines dynamic key-value pairs (FormConfig, FormData)</p><p><strong>Event Types:</strong> Handles form events precisely (handleChange, handleSubmit)</p><p><strong>Type Narrowing:</strong> Conditional rendering by field type (renderField function)</p><p><strong>satisfies:</strong> Type checks while maintaining inference (signUpFormConfig)</p><p><strong>Key Points:</strong></p><ul><li>Complex components can be built by combining small types</li><li>Discriminated Union safely handles various field types</li><li>Generics enable creating reusable components</li><li>The satisfies keyword checks types while maintaining inferred types</li></ul><h3>10. Summary</h3><p>Using React and TypeScript together enables writing safer and more maintainable code. To summarize what we’ve learned:</p><p><strong>Basic Concepts</strong></p><ul><li>Props type definition clarifies component interfaces</li><li>Optional Props create flexible components</li><li>Children and event handlers also get precise types</li></ul><p><strong>Advanced Patterns</strong></p><ul><li>Generic components increase reusability</li><li>Discriminated Union handles conditional Props type-safely</li><li>Custom Hooks also get clear type definitions</li></ul><p><strong>Practical Application</strong></p><ul><li>Start with small types and gradually build complex types</li><li>Use type inference, but write types explicitly when it’s clearer</li><li>Catch errors at compile time to prevent runtime errors</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c5c1d7bf334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Custom Hooks: Designing Reusable Logic]]></title>
            <link>https://medium.com/@dlrnjstjs/mastering-react-custom-hooks-designing-reusable-logic-76a53e16abec?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/76a53e16abec</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[custom-hook]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 16:51:33 GMT</pubDate>
            <atom:updated>2025-10-15T16:51:33.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What are Custom Hooks?</h3><p>While learning React through self-study, one of the most fascinating concepts to discover is custom hooks. At first, you might think “Why do I need to create another function?” But after using them, you’ll realize how powerful this tool really is.</p><p><strong>Custom hooks</strong> are simply your own functions that combine React’s built-in hooks (useState, useEffect, etc.). They let you extract repetitive logic into a single place and reuse it across multiple components.</p><h3>2. Why Use Custom Hooks?</h3><p>Initially, it might seem like you could just extract logic into regular functions. But custom hooks offer some unique advantages:</p><p><strong>Regular Functions:</strong></p><ul><li>Cannot use React hooks</li><li>Difficult to manage state</li><li>Hard to separate from component logic</li><li>Leads to code duplication</li></ul><p><strong>Custom Hooks:</strong></p><ul><li>Can freely use React hooks</li><li>Easy state management</li><li>Perfect logic separation</li><li>Easy code reuse</li></ul><p>Working on projects, you’ll often see the same logic repeated across multiple components, which makes the need for custom hooks clear.</p><h3>3. Rules of Custom Hooks</h3><p>There are essential rules you must follow when creating custom hooks. Breaking these rules will cause errors!</p><h3>Essential Rules</h3><ol><li><strong>Name must start with </strong><strong>use</strong></li></ol><ul><li>✅ useInput, useFetch, useLocalStorage</li><li>❌ getInput, fetchData, localStorage</li></ul><ol><li><strong>Only call at the top level</strong></li></ol><ul><li>Don’t call inside conditions or loops</li><li>Can’t call from regular JavaScript functions</li></ul><ol><li><strong>Only call from React function components or other custom hooks</strong></li></ol><h3>4. Creating Your First Custom Hook</h3><p>Let’s start with the simplest example. We’ll create a custom hook to manage input fields.</p><h4>useInput Hook</h4><pre>import { useState } from &#39;react&#39;;<br><br>// Define custom hook<br>function useInput(initialValue) {<br>  // Manage state<br>  const [value, setValue] = useState(initialValue);<br>  <br>  // Handle input changes<br>  const handleChange = (e) =&gt; {<br>    setValue(e.target.value);<br>  };<br>  <br>  // Reset function<br>  const reset = () =&gt; {<br>    setValue(initialValue);<br>  };<br>  <br>  // Return necessary values as an object<br>  return {<br>    value,      // Current input value<br>    onChange: handleChange,  // Change handler<br>    reset       // Reset function<br>  };<br>}</pre><h4>Usage Example</h4><pre>function LoginForm() {<br>  // Use useInput hook<br>  const email = useInput(&#39;&#39;);<br>  const password = useInput(&#39;&#39;);<br>  <br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    console.log(&#39;Email:&#39;, email.value);<br>    console.log(&#39;Password:&#39;, password.value);<br>    <br>    // Reset after form submission<br>    email.reset();<br>    password.reset();<br>  };<br>  <br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input <br>        type=&quot;email&quot; <br>        placeholder=&quot;Email&quot;<br>        value={email.value}<br>        onChange={email.onChange}<br>      /&gt;<br>      &lt;input <br>        type=&quot;password&quot; <br>        placeholder=&quot;Password&quot;<br>        value={password.value}<br>        onChange={password.onChange}<br>      /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><h4><strong>Why is this better?</strong></h4><ul><li>No need to create separate useState and onChange for each input field</li><li>The reset functionality is reusable</li><li>Code becomes much cleaner!</li></ul><h3>5. Real-World Example: useLocalStorage</h3><p>This is a pattern frequently used in real projects. Let’s create a custom hook to save and retrieve data from localStorage.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useLocalStorage(key, initialValue) {<br>  // Get initial value from localStorage<br>  const [storedValue, setStoredValue] = useState(() =&gt; {<br>    try {<br>      // Find value by key in localStorage<br>      const item = window.localStorage.getItem(key);<br>      // Parse and return if exists, otherwise return initial value<br>      return item ? JSON.parse(item) : initialValue;<br>    } catch (error) {<br>      // Return initial value on error<br>      console.error(&#39;Failed to read from localStorage:&#39;, error);<br>      return initialValue;<br>    }<br>  });<br>  <br>  // Save to localStorage whenever value changes<br>  const setValue = (value) =&gt; {<br>    try {<br>      // Support functional updates<br>      const valueToStore = value instanceof Function <br>        ? value(storedValue) <br>        : value;<br>      <br>      // Update state<br>      setStoredValue(valueToStore);<br>      <br>      // Save to localStorage<br>      window.localStorage.setItem(key, JSON.stringify(valueToStore));<br>    } catch (error) {<br>      console.error(&#39;Failed to save to localStorage:&#39;, error);<br>    }<br>  };<br>  <br>  return [storedValue, setValue];<br>}</pre><h4>Usage Example</h4><pre>function ThemeToggle() {<br>  // Save to localStorage with &#39;theme&#39; key<br>  const [theme, setTheme] = useLocalStorage(&#39;theme&#39;, &#39;light&#39;);<br>  <br>  const toggleTheme = () =&gt; {<br>    // Change from &#39;light&#39; to &#39;dark&#39; and vice versa<br>    setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;);<br>  };<br>  <br>  return (<br>    &lt;div className={`app ${theme}`}&gt;<br>      &lt;h1&gt;Current theme: {theme}&lt;/h1&gt;<br>      &lt;button onClick={toggleTheme}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>Advantages of this hook:</strong></h4><ul><li>Manage localStorage save/load logic in one place</li><li>Includes error handling for safety</li><li>Can be used just like useState</li><li>Data persists even after page refresh!</li></ul><h3>6. Real-World Example: useFetch</h3><p>API calls are needed in almost every project. Making this into a custom hook is incredibly convenient.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useFetch(url) {<br>  // Manage data state<br>  const [data, setData] = useState(null);<br>  // Manage loading state<br>  const [loading, setLoading] = useState(true);<br>  // Manage error state<br>  const [error, setError] = useState(null);<br>  <br>  useEffect(() =&gt; {<br>    // Data fetch function<br>    const fetchData = async () =&gt; {<br>      try {<br>        // Start loading<br>        setLoading(true);<br>        <br>        // Make API call<br>        const response = await fetch(url);<br>        <br>        // Throw error if response is not ok<br>        if (!response.ok) {<br>          throw new Error(`HTTP error! status: ${response.status}`);<br>        }<br>        <br>        // Parse JSON data<br>        const result = await response.json();<br>        <br>        // Save data<br>        setData(result);<br>        // Reset error<br>        setError(null);<br>      } catch (err) {<br>        // Save error<br>        setError(err.message);<br>        // Reset data<br>        setData(null);<br>      } finally {<br>        // End loading<br>        setLoading(false);<br>      }<br>    };<br>    <br>    // Execute function<br>    fetchData();<br>  }, [url]); // Re-run whenever url changes<br>  <br>  // Return three states as an object<br>  return { data, loading, error };<br>}</pre><h4>Usage Example</h4><pre>function UserList() {<br>  // Use useFetch hook<br>  const { data, loading, error } = useFetch(<br>    &#39;https://jsonplaceholder.typicode.com/users&#39;<br>  );<br>  <br>  // While loading<br>  if (loading) {<br>    return &lt;div&gt;Loading...&lt;/div&gt;;<br>  }<br>  <br>  // When error occurs<br>  if (error) {<br>    return &lt;div&gt;Error occurred: {error}&lt;/div&gt;;<br>  }<br>  <br>  // When data is successfully loaded<br>  return (<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>  );<br>}</pre><h4><strong>Why is this useful?</strong></h4><ul><li>API call logic works consistently across all components</li><li>No need to write loading and error handling every time</li><li>Code becomes much cleaner and more readable</li></ul><h3>7. Real-World Example: useDebounce</h3><p>This hook is incredibly useful when building search features. It ensures API calls only happen after the user stops typing.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useDebounce(value, delay) {<br>  // State to store debounced value<br>  const [debouncedValue, setDebouncedValue] = useState(value);<br>  <br>  useEffect(() =&gt; {<br>    // Set timer to update value after delay<br>    const timer = setTimeout(() =&gt; {<br>      setDebouncedValue(value);<br>    }, delay);<br>    <br>    // Cleanup function: remove previous timer when<br>    // component unmounts or when value/delay changes<br>    return () =&gt; {<br>      clearTimeout(timer);<br>    };<br>  }, [value, delay]); // Run whenever value or delay changes<br>  <br>  return debouncedValue;<br>}</pre><h4>Usage Example</h4><pre>function SearchComponent() {<br>  // Search term state<br>  const [searchTerm, setSearchTerm] = useState(&#39;&#39;);<br>  // Debounced search term with 500ms delay<br>  const debouncedSearchTerm = useDebounce(searchTerm, 500);<br>  <br>  // Only call API when debouncedSearchTerm changes<br>  useEffect(() =&gt; {<br>    if (debouncedSearchTerm) {<br>      console.log(&#39;API call:&#39;, debouncedSearchTerm);<br>      // Make actual API call here<br>      // fetch(`/api/search?q=${debouncedSearchTerm}`)<br>    }<br>  }, [debouncedSearchTerm]);<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={searchTerm}<br>        onChange={(e) =&gt; setSearchTerm(e.target.value)}<br>        placeholder=&quot;Enter search term&quot;<br>      /&gt;<br>      &lt;p&gt;Searching for: {searchTerm}&lt;/p&gt;<br>      &lt;p&gt;Actual search: {debouncedSearchTerm}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>How does it work?</strong></h4><ol><li>searchTerm updates immediately as user types</li><li>debouncedSearchTerm updates after 500ms</li><li>If user keeps typing, previous timer is cancelled and new timer starts</li><li>API call only happens 500ms after user stops typing</li></ol><p><strong>Result:</strong> Dramatically reduces the number of API calls!</p><h3>8. Custom Hook Optimization Patterns</h3><h4>8.1. Using with useCallback</h4><pre>import { useState, useCallback } from &#39;react&#39;;<br><br>function useToggle(initialValue = false) {<br>  const [value, setValue] = useState(initialValue);<br>  <br>  // Use useCallback to prevent function from being recreated every time<br>  const toggle = useCallback(() =&gt; {<br>    setValue(v =&gt; !v);<br>  }, []); // Empty dependency array means function is created only once<br>  <br>  return [value, toggle];<br>}</pre><h4><strong>Why use useCallback?</strong></h4><ul><li>The returned toggle function isn&#39;t recreated every time</li><li>Prevents unnecessary re-renders when passing as props to child components</li></ul><h4>8.2. Multiple Return Value Patterns</h4><pre>// Pattern 1: Return as array (similar to useState)<br>function useCounter(initialValue) {<br>  const [count, setCount] = useState(initialValue);<br>  return [count, setCount];<br>}<br><br>// Usage: const [count, setCount] = useCounter(0);<br><br>// Pattern 2: Return as object (more explicit)<br>function useCounter(initialValue) {<br>  const [count, setCount] = useState(initialValue);<br>  const increment = () =&gt; setCount(c =&gt; c + 1);<br>  const decrement = () =&gt; setCount(c =&gt; c - 1);<br>  <br>  return { count, increment, decrement };<br>}<br><br>// Usage: const { count, increment, decrement } = useCounter(0);</pre><h4><strong>Which should you choose?</strong></h4><ul><li>Use array for 1–2 return values</li><li>Use object for 3+ return values (more readable)</li></ul><h3>9. Common Mistakes to Avoid</h3><p>These are mistakes that commonly occur when learning through self-study.</p><h4>9.1. Creating Infinite Loops</h4><pre>// ❌ Wrong example<br>function useFetch(url) {<br>  const [data, setData] = useState(null);<br>  <br>  useEffect(() =&gt; {<br>    fetch(url)<br>      .then(res =&gt; res.json())<br>      .then(setData);<br>  }); // Missing dependency array!<br>  <br>  return data;<br>}</pre><p><strong>Problem:</strong> Without dependency array, fetch runs on every render, and when fetch completes, state updates causing another render — infinite loop!</p><pre>// ✅ Correct example<br>function useFetch(url) {<br>  const [data, setData] = useState(null);<br>  <br>  useEffect(() =&gt; {<br>    fetch(url)<br>      .then(res =&gt; res.json())<br>      .then(setData);<br>  }, [url]); // Only runs when url changes<br>  <br>  return data;<br>}</pre><h4>9.2. Calling Hooks Conditionally</h4><pre>// ❌ Wrong example<br>function useConditional(condition) {<br>  if (condition) {<br>    const [value, setValue] = useState(0); // Hook call inside condition!<br>    return value;<br>  }<br>  return null;<br>}</pre><p><strong>Problem:</strong> React hooks must be called in the same order every time, but placing them inside conditions can change the order.</p><pre>// ✅ Correct example<br>function useConditional(condition) {<br>  const [value, setValue] = useState(0);<br>  <br>  if (condition) {<br>    return value;<br>  }<br>  return null;<br>}</pre><h4>9.3. Ignoring Naming Rules</h4><pre>// ❌ Wrong example - doesn&#39;t start with &#39;use&#39;<br>function getWindowSize() {<br>  const [size, setSize] = useState({<br>    width: window.innerWidth,<br>    height: window.innerHeight<br>  });<br>  return size;<br>}</pre><p><strong>Problem:</strong> React won’t recognize it as a custom hook if it doesn’t start with use, and won&#39;t enforce hook rules.</p><pre>// ✅ Correct example<br>function useWindowSize() {<br>  const [size, setSize] = useState({<br>    width: window.innerWidth,<br>    height: window.innerHeight<br>  });<br>  return size;<br>}</pre><h3>10. Final Thoughts</h3><p>Learning custom hooks through self-study, you’ll realize that while they seem complex at first, they’re actually quite simple once you start building them. And once you create one, you can reuse it everywhere so conveniently.</p><h4>Key Takeaways</h4><p><strong>Things to remember:</strong></p><ul><li>Custom hooks must have names starting with use</li><li>Can freely use React hooks inside</li><li>Powerful tool for reusing logic and keeping code clean</li><li>Great for abstracting repetitive patterns like state management, API calls, event listeners</li></ul><h4>Practical Tips</h4><ol><li><strong>Start small</strong>: Don’t try to build complex hooks first. Start with simple ones like useToggle, useInput.</li><li><strong>Create when actually needed</strong>: It’s good to make a custom hook when the same logic repeats 3+ times.</li><li><strong>Test your hooks</strong>: Custom hooks can be tested like regular functions. Use renderHook from React Testing Library.</li><li><strong>Document your code</strong>: Add comments so you can understand how to use them when you look back later.</li></ol><p>Custom hooks make React more enjoyable to work with. Try building your own and create your personal hook library. You’ll see your code getting cleaner and cleaner!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76a53e16abec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Advanced Patterns: Compound Components & Render Props in Practice]]></title>
            <link>https://medium.com/@dlrnjstjs/react-advanced-patterns-compound-components-render-props-in-practice-edfee12a113e?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/edfee12a113e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 13:53:50 GMT</pubDate>
            <atom:updated>2025-10-09T13:53:50.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>While teaching myself React, I got comfortable with the basics, but when I looked at production code, I kept running into unfamiliar patterns. Especially the way components were composed together or functions passed as props — these were confusing at first.</p><p>In this article, I want to share what I’ve learned about two particularly useful patterns: <strong>Compound Components</strong> and <strong>Render Props</strong>. I’ll walk through the “aha!” moments I had when I realized when and why to use each pattern.</p><h3>Compound Components Pattern</h3><h4>Understanding the Concept</h4><p>Compound Components is a pattern where multiple components work together to provide a single cohesive functionality. Think of HTML’s &lt;select&gt; and &lt;option&gt; tags.</p><pre>&lt;select&gt;<br>  &lt;option value=&quot;1&quot;&gt;Option 1&lt;/option&gt;<br>  &lt;option value=&quot;2&quot;&gt;Option 2&lt;/option&gt;<br>&lt;/select&gt;</pre><p>&lt;select&gt; and &lt;option&gt; don&#39;t mean much separately, but together they create a complete dropdown menu. Compound Components work the same way.</p><h4>Basic Example</h4><p>Let’s start with a simple toggle component.</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>// 1. Create Context - a channel for sharing state<br>const ToggleContext = createContext();<br><br>// 2. Main component<br>function Toggle({ children }) {<br>  // Manage toggle state and state-changing function<br>  const [on, setOn] = useState(false);<br>  <br>  // toggle function to switch on/off state<br>  const toggle = () =&gt; setOn(!on);<br>  <br>  // Provide state access to child components through Context<br>  return (<br>    &lt;ToggleContext.Provider value={{ on, toggle }}&gt;<br>      {children}<br>    &lt;/ToggleContext.Provider&gt;<br>  );<br>}<br><br>// 3. Toggle button component<br>Toggle.Button = function ToggleButton({ children }) {<br>  // Get toggle function from Context<br>  const { toggle } = useContext(ToggleContext);<br>  <br>  return &lt;button onClick={toggle}&gt;{children}&lt;/button&gt;;<br>};<br><br>// 4. Component to display toggle state<br>Toggle.Display = function ToggleDisplay() {<br>  // Get on state from Context<br>  const { on } = useContext(ToggleContext);<br>  <br>  return &lt;div&gt;{on ? &#39;ON ✅&#39; : &#39;OFF ❌&#39;}&lt;/div&gt;;<br>};<br><br>// Usage example<br>function App() {<br>  return (<br>    &lt;Toggle&gt;<br>      &lt;Toggle.Button&gt;Toggle Button&lt;/Toggle.Button&gt;<br>      &lt;Toggle.Display /&gt;<br>    &lt;/Toggle&gt;<br>  );<br>}</pre><p><strong>Code Explanation:</strong></p><ul><li>The Toggle component manages state and provides Context</li><li>Toggle.Button and Toggle.Display access shared state through Context</li><li>Each component is independent but provides complete functionality when used together</li><li>When using them, you can arrange them like LEGO blocks in any combination you want</li></ul><h4>Real-World Application</h4><p>In practice, I found this particularly useful when building complex tab menus.</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>const TabContext = createContext();<br><br>// Main tab container<br>function Tabs({ children, defaultTab }) {<br>  const [activeTab, setActiveTab] = useState(defaultTab);<br>  <br>  return (<br>    &lt;TabContext.Provider value={{ activeTab, setActiveTab }}&gt;<br>      &lt;div className=&quot;tabs-container&quot;&gt;<br>        {children}<br>      &lt;/div&gt;<br>    &lt;/TabContext.Provider&gt;<br>  );<br>}<br><br>// List wrapper for tab buttons<br>Tabs.List = function TabList({ children }) {<br>  return (<br>    &lt;div className=&quot;tab-list&quot; style={{ <br>      display: &#39;flex&#39;, <br>      gap: &#39;8px&#39;, <br>      borderBottom: &#39;2px solid #e0e0e0&#39;,<br>      marginBottom: &#39;16px&#39;<br>    }}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Individual tab button<br>Tabs.Tab = function Tab({ id, children }) {<br>  const { activeTab, setActiveTab } = useContext(TabContext);<br>  const isActive = activeTab === id;<br>  <br>  return (<br>    &lt;button<br>      onClick={() =&gt; setActiveTab(id)}<br>      style={{<br>        padding: &#39;12px 24px&#39;,<br>        border: &#39;none&#39;,<br>        background: isActive ? &#39;#007bff&#39; : &#39;transparent&#39;,<br>        color: isActive ? &#39;white&#39; : &#39;#333&#39;,<br>        cursor: &#39;pointer&#39;,<br>        borderRadius: &#39;4px 4px 0 0&#39;,<br>        fontWeight: isActive ? &#39;bold&#39; : &#39;normal&#39;<br>      }}<br>    &gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>};<br><br>// Container for tab content<br>Tabs.Panels = function TabPanels({ children }) {<br>  return &lt;div className=&quot;tab-panels&quot;&gt;{children}&lt;/div&gt;;<br>};<br><br>// Individual tab panel<br>Tabs.Panel = function TabPanel({ id, children }) {<br>  const { activeTab } = useContext(TabContext);<br>  <br>  // Don&#39;t render if not the active tab<br>  if (activeTab !== id) return null;<br>  <br>  return (<br>    &lt;div className=&quot;tab-panel&quot; style={{ padding: &#39;16px&#39; }}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Usage example<br>function UserProfile() {<br>  return (<br>    &lt;Tabs defaultTab=&quot;profile&quot;&gt;<br>      &lt;Tabs.List&gt;<br>        &lt;Tabs.Tab id=&quot;profile&quot;&gt;Profile&lt;/Tabs.Tab&gt;<br>        &lt;Tabs.Tab id=&quot;posts&quot;&gt;Posts&lt;/Tabs.Tab&gt;<br>        &lt;Tabs.Tab id=&quot;settings&quot;&gt;Settings&lt;/Tabs.Tab&gt;<br>      &lt;/Tabs.List&gt;<br>      <br>      &lt;Tabs.Panels&gt;<br>        &lt;Tabs.Panel id=&quot;profile&quot;&gt;<br>          &lt;h2&gt;User Profile&lt;/h2&gt;<br>          &lt;p&gt;Name, email, and other info...&lt;/p&gt;<br>        &lt;/Tabs.Panel&gt;<br>        <br>        &lt;Tabs.Panel id=&quot;posts&quot;&gt;<br>          &lt;h2&gt;My Posts&lt;/h2&gt;<br>          &lt;p&gt;List of posts...&lt;/p&gt;<br>        &lt;/Tabs.Panel&gt;<br>        <br>        &lt;Tabs.Panel id=&quot;settings&quot;&gt;<br>          &lt;h2&gt;Settings&lt;/h2&gt;<br>          &lt;p&gt;Account settings options...&lt;/p&gt;<br>        &lt;/Tabs.Panel&gt;<br>      &lt;/Tabs.Panels&gt;<br>    &lt;/Tabs&gt;<br>  );<br>}</pre><h4><strong>Why is this pattern good?</strong></h4><ul><li><strong>Flexibility</strong>: You can freely adjust the order and number of tabs</li><li><strong>Readability</strong>: The structure is immediately clear when reading the code</li><li><strong>Reusability</strong>: The Tabs component can be used anywhere with the same API</li><li><strong>Extensibility</strong>: Easy to add new features (animations, accessibility, etc.)</li></ul><h3>Render Props Pattern</h3><h4>Understanding the Concept</h4><p>Render Props is a pattern where a component delegates the decision of what to render to the consumer. It receives a function as a prop and renders whatever that function returns.</p><p>At first, I thought “Why pass a function as a prop?” But it proved incredibly useful for separating logic from UI.</p><h4>Basic Example</h4><p>Let’s start with a simple example that tracks mouse position.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>// Component that tracks mouse position<br>function MouseTracker({ render }) {<br>  const [position, setPosition] = useState({ x: 0, y: 0 });<br>  <br>  useEffect(() =&gt; {<br>    // Mouse move event handler<br>    const handleMouseMove = (event) =&gt; {<br>      setPosition({<br>        x: event.clientX,<br>        y: event.clientY<br>      });<br>    };<br>    <br>    // Register event listener<br>    window.addEventListener(&#39;mousemove&#39;, handleMouseMove);<br>    <br>    // Remove event listener when component unmounts<br>    return () =&gt; {<br>      window.removeEventListener(&#39;mousemove&#39;, handleMouseMove);<br>    };<br>  }, []);<br>  <br>  // Pass position to render function and render its result<br>  return render(position);<br>}<br><br>// Usage example 1: Display coordinates as text<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Move your mouse!&lt;/h1&gt;<br>      &lt;MouseTracker <br>        render={(position) =&gt; (<br>          &lt;p&gt;<br>            Current mouse position: X={position.x}, Y={position.y}<br>          &lt;/p&gt;<br>        )}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Usage example 2: Cat emoji follows the mouse<br>function AppWithCat() {<br>  return (<br>    &lt;div style={{ height: &#39;100vh&#39; }}&gt;<br>      &lt;h1&gt;The cat follows your mouse 🐱&lt;/h1&gt;<br>      &lt;MouseTracker <br>        render={(position) =&gt; (<br>          &lt;div style={{<br>            position: &#39;absolute&#39;,<br>            left: position.x,<br>            top: position.y,<br>            transform: &#39;translate(-50%, -50%)&#39;,<br>            fontSize: &#39;40px&#39;<br>          }}&gt;<br>            🐱<br>          &lt;/div&gt;<br>        )}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>Code Explanation:</strong></h4><ul><li>MouseTracker handles only the <strong>logic</strong> of tracking mouse position</li><li>How to display it is determined by the function passed as the render prop</li><li>The same logic can create completely different UIs</li><li>You receive the position data and can use it however you want</li></ul><h4>Real-World Application</h4><p>In production, I found this especially useful for reusing data fetching logic.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>// Component responsible for data fetching logic<br>function DataFetcher({ url, render }) {<br>  const [data, setData] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br>  <br>  useEffect(() =&gt; {<br>    // Fetch data<br>    const fetchData = async () =&gt; {<br>      try {<br>        setLoading(true);<br>        const response = await fetch(url);<br>        <br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch data&#39;);<br>        }<br>        <br>        const result = await response.json();<br>        setData(result);<br>        setError(null);<br>      } catch (err) {<br>        setError(err.message);<br>        setData(null);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br>    <br>    fetchData();<br>  }, [url]); // Re-run when url changes<br>  <br>  // Pass loading, error, and data states to render function<br>  return render({ data, loading, error });<br>}<br><br>// Usage example 1: User list<br>function UserList() {<br>  return (<br>    &lt;DataFetcher<br>      url=&quot;https://jsonplaceholder.typicode.com/users&quot;<br>      render={({ data, loading, error }) =&gt; {<br>        // While loading<br>        if (loading) {<br>          return &lt;div&gt;Loading user list...&lt;/div&gt;;<br>        }<br>        <br>        // When error occurs<br>        if (error) {<br>          return &lt;div style={{ color: &#39;red&#39; }}&gt;Error: {error}&lt;/div&gt;;<br>        }<br>        <br>        // When data is successfully loaded<br>        return (<br>          &lt;div&gt;<br>            &lt;h2&gt;User List&lt;/h2&gt;<br>            &lt;ul&gt;<br>              {data.map(user =&gt; (<br>                &lt;li key={user.id}&gt;<br>                  {user.name} - {user.email}<br>                &lt;/li&gt;<br>              ))}<br>            &lt;/ul&gt;<br>          &lt;/div&gt;<br>        );<br>      }}<br>    /&gt;<br>  );<br>}<br><br>// Usage example 2: Post list (same logic, different UI)<br>function PostList() {<br>  return (<br>    &lt;DataFetcher<br>      url=&quot;https://jsonplaceholder.typicode.com/posts&quot;<br>      render={({ data, loading, error }) =&gt; {<br>        if (loading) {<br>          return (<br>            &lt;div style={{ textAlign: &#39;center&#39;, padding: &#39;20px&#39; }}&gt;<br>              &lt;div className=&quot;spinner&quot;&gt;⏳ Loading...&lt;/div&gt;<br>            &lt;/div&gt;<br>          );<br>        }<br>        <br>        if (error) {<br>          return (<br>            &lt;div style={{ <br>              background: &#39;#ffebee&#39;, <br>              padding: &#39;16px&#39;, <br>              borderRadius: &#39;4px&#39; <br>            }}&gt;<br>              ⚠️ {error}<br>            &lt;/div&gt;<br>          );<br>        }<br>        <br>        return (<br>          &lt;div&gt;<br>            &lt;h2&gt;Post List&lt;/h2&gt;<br>            &lt;div style={{ display: &#39;grid&#39;, gap: &#39;16px&#39; }}&gt;<br>              {data.slice(0, 5).map(post =&gt; (<br>                &lt;div key={post.id} style={{<br>                  border: &#39;1px solid #ddd&#39;,<br>                  padding: &#39;16px&#39;,<br>                  borderRadius: &#39;8px&#39;<br>                }}&gt;<br>                  &lt;h3&gt;{post.title}&lt;/h3&gt;<br>                  &lt;p&gt;{post.body}&lt;/p&gt;<br>                &lt;/div&gt;<br>              ))}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        );<br>      }}<br>    /&gt;<br>  );<br>}</pre><h4><strong>Why is this pattern good?</strong></h4><ul><li><strong>Logic Reusability</strong>: Write data fetching logic once and use it everywhere</li><li><strong>UI Freedom</strong>: Display the same data in completely different ways</li><li><strong>Separation of Concerns</strong>: Clearly separate fetching data from displaying it</li><li><strong>Testability</strong>: Test logic and UI independently</li></ul><h4>Variation Using Children as Function</h4><p>Render Props can also be used by receiving children as a function. Personally, I found this approach more readable.</p><pre>function DataFetcher({ url, children }) {<br>  const [data, setData] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br>  <br>  // ... same logic as above<br>  <br>  // If children is a function, execute it and return the result<br>  return children({ data, loading, error });<br>}<br><br>// Usage style<br>function App() {<br>  return (<br>    &lt;DataFetcher url=&quot;https://api.example.com/data&quot;&gt;<br>      {({ data, loading, error }) =&gt; {<br>        if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>        if (error) return &lt;div&gt;Error: {error}&lt;/div&gt;;<br>        return &lt;div&gt;Data: {JSON.stringify(data)}&lt;/div&gt;;<br>      }}<br>    &lt;/DataFetcher&gt;<br>  );<br>}</pre><h3>Comparing the Two Patterns</h3><p>Here are the differences I noticed from using both patterns in practice.</p><h4>Choose Compound Components when:</h4><ul><li>Multiple components need to <strong>closely collaborate</strong></li><li>The UI structure is clear and <strong>hierarchical</strong></li><li>Users should <strong>freely compose</strong> component combinations</li><li>Examples: tabs, modals, dropdowns, accordions, etc.</li></ul><h4>Choose Render Props when:</h4><ul><li>You want to <strong>reuse only logic</strong> with different UIs each time</li><li>You provide data or state, and let <strong>users decide</strong> how to display it</li><li>The same functionality needs to be used in <strong>various forms</strong> across different places</li><li>Examples: data fetching, mouse tracking, form management, timers, etc.</li></ul><h4>Side-by-Side Comparison</h4><p><strong>Primary Purpose</strong></p><ul><li>Compound Components: UI structure composition</li><li>Render Props: Logic reusability</li></ul><p><strong>Learning Curve</strong></p><ul><li>Compound Components: Medium difficulty</li><li>Render Props: Difficult at first, but easier once you get familiar with it</li></ul><p><strong>Code Readability</strong></p><ul><li>Compound Components: Very good (declarative and clear structure)</li><li>Render Props: Medium (can get complex when nested)</li></ul><p><strong>Flexibility</strong></p><ul><li>Compound Components: High (freedom in structural composition)</li><li>Render Props: Very high (complete freedom over UI rendering)</li></ul><p><strong>Typical Use Cases</strong></p><ul><li>Compound Components: UI components like tabs, modals, dropdowns</li><li>Render Props: Logic components like data fetching, mouse tracking, timers</li></ul><h3>Conclusion</h3><p>When I first encountered these patterns, I thought “Why make things so complicated?” But after using them myself, I understood the specific problems each pattern solves, and I saw significant improvements in code reusability and maintainability.</p><p>Compound Components proved particularly useful when building UI libraries, while Render Props shined when abstracting common logic.</p><p>Of course, you don’t need to force these patterns into every situation. For simple components, just receiving props and rendering is often better. But when components become complex and reusability becomes important, knowing these patterns helps you write much cleaner code.</p><p>I encourage you to try applying these patterns in your actual projects and discover your own use cases. When you’re writing code and think “This part is repetitive…” — that’s when you should remember these patterns!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edfee12a113e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Scalable React Architecture: A Guide to Large-Scale Application Structure]]></title>
            <link>https://medium.com/@dlrnjstjs/designing-scalable-react-architecture-a-guide-to-large-scale-application-structure-2eac48a4406f?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eac48a4406f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 03:08:31 GMT</pubDate>
            <atom:updated>2025-10-02T03:08:31.515Z</atom:updated>
            <content:encoded><![CDATA[<p>Building large-scale React applications requires more than just writing functional components and managing state. The key to success lies in establishing a <strong>scalable, maintainable architecture</strong> that can grow with your team and product requirements. Poor architectural decisions can lead to technical debt, reduced development velocity, and increased onboarding time for new developers.</p><p>In this comprehensive guide, I’ll walk you through production-tested React project structures and patterns that have been proven to work in real-world applications.</p><h3>Foundation: Project Structure Overview</h3><pre>src/<br>├── components/           # Reusable UI components<br>│   ├── ui/              # Basic UI primitives (Button, Input, etc.)<br>│   ├── layout/          # Layout components<br>│   └── common/          # Shared components<br>├── features/            # Feature-based modules<br>│   ├── auth/<br>│   ├── dashboard/<br>│   └── user-management/<br>├── hooks/               # Custom hooks<br>├── services/            # API and external services<br>├── store/               # State management<br>├── utils/               # Utility functions<br>├── constants/           # Application constants<br>├── types/               # TypeScript type definitions<br>└── assets/              # Static assets</pre><h3>Designing Scalable React Architecture: A Guide to Large-Scale Application Structure</h3><p>Building large-scale React applications requires more than just writing functional components and managing state. The key to success lies in establishing a <strong>scalable, maintainable architecture</strong> that can grow with your team and product requirements. Poor architectural decisions can lead to technical debt, reduced development velocity, and increased onboarding time for new developers.</p><p>In this comprehensive guide, I’ll walk you through production-tested React project structures and patterns that have been proven to work in real-world applications.</p><h4>Table of Contents</h4><ol><li><a href="#%EF%B8%8F-foundation-project-structure-overview">Foundation: Project Structure Overview</a></li><li><a href="#-feature-based-architecture">Feature-Based Architecture</a></li><li><a href="#-common-component-design">Common Component Design</a></li><li><a href="#-utilities-and-helper-functions">Utilities and Helper Functions</a></li><li><a href="#-state-management-strategy">State Management Strategy</a></li><li><a href="#%EF%B8%8F-routing-structure">Routing Structure</a></li><li><a href="#-testing-strategy">Testing Strategy</a></li><li><a href="#-performance-optimization">Performance Optimization</a></li><li><a href="#-security-considerations">Security Considerations</a></li><li><a href="#-deployment-optimization">Deployment Optimization</a></li><li><a href="#conclusion">Conclusion</a></li></ol><h3>1. Foundation: Project Structure Overview</h3><pre>src/<br>├── components/           # Reusable UI components<br>│   ├── ui/              # Basic UI primitives (Button, Input, etc.)<br>│   ├── layout/          # Layout components<br>│   └── common/          # Shared components<br>├── features/            # Feature-based modules<br>│   ├── auth/<br>│   ├── dashboard/<br>│   └── user-management/<br>├── hooks/               # Custom hooks<br>├── services/            # API and external services<br>├── store/               # State management<br>├── utils/               # Utility functions<br>├── constants/           # Application constants<br>├── types/               # TypeScript type definitions<br>└── assets/              # Static assets</pre><p>This structure follows the <strong>Separation of Concerns</strong> principle, where each directory has a clear, single responsibility. The architecture is designed to scale horizontally as your application grows.</p><h3>2. Feature-Based Architecture</h3><p>The most critical design principle is adopting a <strong>feature-based (domain-driven)</strong> structure:</p><pre>src/features/auth/<br>├── components/          # Authentication-related components<br>│   ├── LoginForm.tsx<br>│   ├── SignupForm.tsx<br>│   └── index.ts<br>├── hooks/               # Authentication hooks<br>│   ├── useAuth.ts<br>│   ├── useLogin.ts<br>│   └── index.ts<br>├── services/            # Authentication API<br>│   ├── authApi.ts<br>│   └── index.ts<br>├── store/               # Authentication state management<br>│   ├── authSlice.ts<br>│   └── index.ts<br>├── types/               # Authentication-related types<br>│   ├── auth.types.ts<br>│   └── index.ts<br>└── index.ts             # Feature entry point</pre><p><strong>Feature Module Implementation Example</strong></p><pre>// src/features/auth/types/auth.types.ts<br>export interface User {<br>  id: string;<br>  email: string;<br>  name: string;<br>  role: &#39;admin&#39; | &#39;user&#39;;<br>}<br><br>export interface LoginCredentials {<br>  email: string;<br>  password: string;<br>}<br><br>export interface AuthState {<br>  user: User | null;<br>  isLoading: boolean;<br>  error: string | null;<br>}</pre><p><strong>Importance of Type Definitions</strong>: Using TypeScript helps catch errors at compile time and enables powerful IDE features like autocomplete and refactoring. Separating types by feature creates clear boundaries and improves code maintainability.</p><pre>// src/features/auth/services/authApi.ts<br>import { api } from &#39;@/services/api&#39;;<br>import { LoginCredentials, User } from &#39;../types&#39;;<br><br>export class AuthService {<br>  static async login(credentials: LoginCredentials): Promise&lt;User&gt; {<br>    const response = await api.post(&#39;/auth/login&#39;, credentials);<br>    return response.data;<br>  }<br><br>  static async getCurrentUser(): Promise&lt;User&gt; {<br>    const response = await api.get(&#39;/auth/me&#39;);<br>    return response.data;<br>  }<br><br>  static async logout(): Promise&lt;void&gt; {<br>    await api.post(&#39;/auth/logout&#39;);<br>  }<br>}</pre><p><strong>Service Layer Pattern</strong>: Separating API calls into dedicated service classes creates a clear boundary between business logic and data access. This makes the codebase more testable and easier to maintain when API contracts change.</p><pre>// src/features/auth/hooks/useAuth.ts<br>import { useQuery, useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br>import { AuthService } from &#39;../services/authApi&#39;;<br>import { LoginCredentials } from &#39;../types&#39;;<br><br>export const useAuth = () =&gt; {<br>  const queryClient = useQueryClient();<br><br>  const { data: user, isLoading } = useQuery({<br>    queryKey: [&#39;auth&#39;, &#39;currentUser&#39;],<br>    queryFn: AuthService.getCurrentUser,<br>    staleTime: 5 * 60 * 1000, // 5 minutes<br>  });<br><br>  const loginMutation = useMutation({<br>    mutationFn: AuthService.login,<br>    onSuccess: (user) =&gt; {<br>      queryClient.setQueryData([&#39;auth&#39;, &#39;currentUser&#39;], user);<br>      queryClient.invalidateQueries({ queryKey: [&#39;auth&#39;] });<br>    },<br>  });<br><br>  const logoutMutation = useMutation({<br>    mutationFn: AuthService.logout,<br>    onSuccess: () =&gt; {<br>      queryClient.clear();<br>    },<br>  });<br><br>  return {<br>    user,<br>    isLoading,<br>    isAuthenticated: !!user,<br>    login: loginMutation.mutateAsync,<br>    logout: logoutMutation.mutateAsync,<br>    isLoggingIn: loginMutation.isPending,<br>  };<br>};</pre><p><strong>Custom Hooks for State Management</strong>: Using React Query for server state management and wrapping it in custom hooks creates reusable logic that keeps components pure and focused on rendering.</p><h3>3. Common Component Design</h3><pre>// src/components/ui/Button/Button.tsx<br>import React from &#39;react&#39;;<br>import { cn } from &#39;@/utils/className&#39;;<br><br>export interface ButtonProps <br>  extends React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt; {<br>  variant?: &#39;primary&#39; | &#39;secondary&#39; | &#39;danger&#39; | &#39;ghost&#39;;<br>  size?: &#39;sm&#39; | &#39;md&#39; | &#39;lg&#39;;<br>  isLoading?: boolean;<br>  leftIcon?: React.ReactNode;<br>  rightIcon?: React.ReactNode;<br>}<br><br>export const Button: React.FC&lt;ButtonProps&gt; = ({<br>  children,<br>  variant = &#39;primary&#39;,<br>  size = &#39;md&#39;,<br>  isLoading = false,<br>  leftIcon,<br>  rightIcon,<br>  className,<br>  disabled,<br>  ...props<br>}) =&gt; {<br>  const baseClasses = &#39;inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2&#39;;<br>  <br>  const variants = {<br>    primary: &#39;bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500&#39;,<br>    secondary: &#39;bg-gray-200 text-gray-900 hover:bg-gray-300 focus:ring-gray-500&#39;,<br>    danger: &#39;bg-red-600 text-white hover:bg-red-700 focus:ring-red-500&#39;,<br>    ghost: &#39;bg-transparent text-gray-700 hover:bg-gray-100 focus:ring-gray-500&#39;,<br>  };<br><br>  const sizes = {<br>    sm: &#39;px-3 py-1.5 text-sm&#39;,<br>    md: &#39;px-4 py-2 text-base&#39;,<br>    lg: &#39;px-6 py-3 text-lg&#39;,<br>  };<br><br>  return (<br>    &lt;button<br>      className={cn(<br>        baseClasses,<br>        variants[variant],<br>        sizes[size],<br>        (disabled || isLoading) &amp;&amp; &#39;opacity-50 cursor-not-allowed&#39;,<br>        className<br>      )}<br>      disabled={disabled || isLoading}<br>      {...props}<br>    &gt;<br>      {isLoading ? (<br>        &lt;div className=&quot;w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin mr-2&quot; /&gt;<br>      ) : (<br>        leftIcon &amp;&amp; &lt;span className=&quot;mr-2&quot;&gt;{leftIcon}&lt;/span&gt;<br>      )}<br>      {children}<br>      {rightIcon &amp;&amp; &lt;span className=&quot;ml-2&quot;&gt;{rightIcon}&lt;/span&gt;}<br>    &lt;/button&gt;<br>  );<br>};</pre><p><strong>Component Design Principles</strong>:</p><ul><li><strong>Composability</strong>: Design components to work well together through props composition</li><li><strong>Accessibility</strong>: Follow WAI-ARIA guidelines for inclusive design</li><li><strong>Extensibility</strong>: Inherit all native HTML attributes for maximum flexibility</li><li><strong>Consistency</strong>: Use design system tokens for consistent UI</li></ul><pre>// src/components/ui/Button/index.ts<br>export { Button, type ButtonProps } from &#39;./Button&#39;;<br>export { IconButton } from &#39;./IconButton&#39;;<br>export { ButtonGroup } from &#39;./ButtonGroup&#39;;</pre><p><strong>Barrel Export Pattern</strong>: Each component folder exports all related elements through an index.ts file. This creates clean import statements and minimizes the impact of internal structure changes.</p><h3>4. Utilities and Helper Functions</h3><pre>// src/utils/className.ts<br>import { clsx, type ClassValue } from &#39;clsx&#39;;<br>import { twMerge } from &#39;tailwind-merge&#39;;<br><br>/**<br> * Combines Tailwind CSS classes conditionally and removes duplicates<br> * @param inputs - Class names to combine<br> * @returns Combined class string<br> */<br>export function cn(...inputs: ClassValue[]): string {<br>  return twMerge(clsx(inputs));<br>}</pre><pre>// src/utils/api.ts<br>import axios, { AxiosInstance, AxiosResponse } from &#39;axios&#39;;<br><br>class ApiClient {<br>  private client: AxiosInstance;<br><br>  constructor() {<br>    this.client = axios.create({<br>      baseURL: process.env.REACT_APP_API_URL,<br>      timeout: 10000,<br>    });<br><br>    this.setupInterceptors();<br>  }<br><br>  private setupInterceptors(): void {<br>    // Request interceptor<br>    this.client.interceptors.request.use(<br>      (config) =&gt; {<br>        const token = localStorage.getItem(&#39;accessToken&#39;);<br>        if (token) {<br>          config.headers.Authorization = `Bearer ${token}`;<br>        }<br>        return config;<br>      },<br>      (error) =&gt; Promise.reject(error)<br>    );<br><br>    // Response interceptor<br>    this.client.interceptors.response.use(<br>      (response: AxiosResponse) =&gt; response,<br>      async (error) =&gt; {<br>        if (error.response?.status === 401) {<br>          // Handle token expiration<br>          localStorage.removeItem(&#39;accessToken&#39;);<br>          window.location.href = &#39;/login&#39;;<br>        }<br>        return Promise.reject(error);<br>      }<br>    );<br>  }<br><br>  async get&lt;T&gt;(url: string): Promise&lt;T&gt; {<br>    const response = await this.client.get&lt;T&gt;(url);<br>    return response.data;<br>  }<br><br>  async post&lt;T&gt;(url: string, data?: any): Promise&lt;T&gt; {<br>    const response = await this.client.post&lt;T&gt;(url, data);<br>    return response.data;<br>  }<br><br>  async put&lt;T&gt;(url: string, data?: any): Promise&lt;T&gt; {<br>    const response = await this.client.put&lt;T&gt;(url, data);<br>    return response.data;<br>  }<br><br>  async delete&lt;T&gt;(url: string): Promise&lt;T&gt; {<br>    const response = await this.client.delete&lt;T&gt;(url);<br>    return response.data;<br>  }<br>}<br><br>export const api = new ApiClient();</pre><p><strong>API Client Pattern Benefits</strong>:</p><ul><li><strong>Centralized Configuration</strong>: All API calls share common settings managed in one place</li><li><strong>Interceptor Utilization</strong>: Automatic handling of authentication, logging, and error processing</li><li><strong>Type Safety</strong>: Generic types ensure response type safety throughout the application</li></ul><h3>5. State Management Strategy</h3><pre>// src/store/index.ts<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import { authSlice } from &#39;@/features/auth/store/authSlice&#39;;<br>import { uiSlice } from &#39;./slices/uiSlice&#39;;<br><br>export const store = configureStore({<br>  reducer: {<br>    auth: authSlice.reducer,<br>    ui: uiSlice.reducer,<br>  },<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware({<br>      serializableCheck: {<br>        ignoredActions: [&#39;persist/PERSIST&#39;],<br>      },<br>    }),<br>});<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br>export type AppDispatch = typeof store.dispatch;</pre><pre>// src/store/slices/uiSlice.ts<br>import { createSlice, PayloadAction } from &#39;@reduxjs/toolkit&#39;;<br><br>interface UiState {<br>  sidebarOpen: boolean;<br>  theme: &#39;light&#39; | &#39;dark&#39;;<br>  notifications: Notification[];<br>}<br><br>interface Notification {<br>  id: string;<br>  type: &#39;success&#39; | &#39;error&#39; | &#39;warning&#39; | &#39;info&#39;;<br>  message: string;<br>  duration?: number;<br>}<br><br>const initialState: UiState = {<br>  sidebarOpen: true,<br>  theme: &#39;light&#39;,<br>  notifications: [],<br>};<br><br>export const uiSlice = createSlice({<br>  name: &#39;ui&#39;,<br>  initialState,<br>  reducers: {<br>    toggleSidebar: (state) =&gt; {<br>      state.sidebarOpen = !state.sidebarOpen;<br>    },<br>    setTheme: (state, action: PayloadAction&lt;&#39;light&#39; | &#39;dark&#39;&gt;) =&gt; {<br>      state.theme = action.payload;<br>    },<br>    addNotification: (state, action: PayloadAction&lt;Omit&lt;Notification, &#39;id&#39;&gt;&gt;) =&gt; {<br>      const notification: Notification = {<br>        id: Date.now().toString(),<br>        ...action.payload,<br>      };<br>      state.notifications.push(notification);<br>    },<br>    removeNotification: (state, action: PayloadAction&lt;string&gt;) =&gt; {<br>      state.notifications = state.notifications.filter(<br>        (notification) =&gt; notification.id !== action.payload<br>      );<br>    },<br>  },<br>});<br><br>export const { toggleSidebar, setTheme, addNotification, removeNotification } = uiSlice.actions;</pre><p><strong>State Management Guidelines</strong>:</p><ul><li><strong>Local State</strong>: Use useState, useReducer for component-specific state</li><li><strong>Server State</strong>: Use React Query or SWR for API data management</li><li><strong>Global Client State</strong>: Use Redux Toolkit for application-wide state</li><li><strong>URL State</strong>: Leverage React Router’s params and query strings</li></ul><h3>6. Routing Structure</h3><pre>// src/router/index.tsx<br>import { createBrowserRouter } from &#39;react-router-dom&#39;;<br>import { RootLayout } from &#39;@/components/layout/RootLayout&#39;;<br>import { AuthGuard } from &#39;@/components/auth/AuthGuard&#39;;<br>import { lazy } from &#39;react&#39;;<br><br>// Code splitting with lazy loading<br>const Dashboard = lazy(() =&gt; import(&#39;@/features/dashboard/pages/Dashboard&#39;));<br>const Profile = lazy(() =&gt; import(&#39;@/features/auth/pages/Profile&#39;));<br>const Login = lazy(() =&gt; import(&#39;@/features/auth/pages/Login&#39;));<br><br>export const router = createBrowserRouter([<br>  {<br>    path: &#39;/&#39;,<br>    element: &lt;RootLayout /&gt;,<br>    children: [<br>      {<br>        index: true,<br>        element: &lt;AuthGuard&gt;&lt;Dashboard /&gt;&lt;/AuthGuard&gt;,<br>      },<br>      {<br>        path: &#39;profile&#39;,<br>        element: &lt;AuthGuard&gt;&lt;Profile /&gt;&lt;/AuthGuard&gt;,<br>      },<br>      {<br>        path: &#39;login&#39;,<br>        element: &lt;Login /&gt;,<br>      },<br>    ],<br>  },<br>]);</pre><pre>// src/components/auth/AuthGuard.tsx<br>import React from &#39;react&#39;;<br>import { Navigate, useLocation } from &#39;react-router-dom&#39;;<br>import { useAuth } from &#39;@/features/auth/hooks/useAuth&#39;;<br>import { LoadingSpinner } from &#39;@/components/ui/LoadingSpinner&#39;;<br><br>interface AuthGuardProps {<br>  children: React.ReactNode;<br>  requiredRole?: string[];<br>}<br><br>export const AuthGuard: React.FC&lt;AuthGuardProps&gt; = ({ <br>  children, <br>  requiredRole <br>}) =&gt; {<br>  const { user, isLoading } = useAuth();<br>  const location = useLocation();<br><br>  if (isLoading) {<br>    return &lt;LoadingSpinner /&gt;;<br>  }<br><br>  if (!user) {<br>    return &lt;Navigate to=&quot;/login&quot; state={{ from: location }} replace /&gt;;<br>  }<br><br>  if (requiredRole &amp;&amp; !requiredRole.includes(user.role)) {<br>    return &lt;Navigate to=&quot;/unauthorized&quot; replace /&gt;;<br>  }<br><br>  return &lt;&gt;{children}&lt;/&gt;;<br>};</pre><p><strong>Routing Optimization Techniques</strong>:</p><ul><li><strong>Code Splitting</strong>: Lazy loading reduces initial bundle size</li><li><strong>Authentication Guards</strong>: HOC pattern for route protection</li><li><strong>Nested Routing</strong>: Efficient structure using layout components</li></ul><h3>7. Testing Strategy</h3><pre>// src/features/auth/components/__tests__/LoginForm.test.tsx<br>import { render, screen, fireEvent, waitFor } from &#39;@testing-library/react&#39;;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { LoginForm } from &#39;../LoginForm&#39;;<br>import { AuthService } from &#39;../../services/authApi&#39;;<br><br>// Mocking<br>jest.mock(&#39;../../services/authApi&#39;);<br><br>const createWrapper = () =&gt; {<br>  const queryClient = new QueryClient({<br>    defaultOptions: {<br>      queries: { retry: false },<br>      mutations: { retry: false },<br>    },<br>  });<br><br>  return ({ children }: { children: React.ReactNode }) =&gt; (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      {children}<br>    &lt;/QueryClientProvider&gt;<br>  );<br>};<br><br>describe(&#39;LoginForm&#39;, () =&gt; {<br>  beforeEach(() =&gt; {<br>    jest.clearAllMocks();<br>  });<br><br>  it(&#39;should render login form correctly&#39;, () =&gt; {<br>    render(&lt;LoginForm /&gt;, { wrapper: createWrapper() });<br>    <br>    expect(screen.getByLabelText(/email/i)).toBeInTheDocument();<br>    expect(screen.getByLabelText(/password/i)).toBeInTheDocument();<br>    expect(screen.getByRole(&#39;button&#39;, { name: /login/i })).toBeInTheDocument();<br>  });<br><br>  it(&#39;should validate form inputs&#39;, async () =&gt; {<br>    render(&lt;LoginForm /&gt;, { wrapper: createWrapper() });<br>    <br>    const submitButton = screen.getByRole(&#39;button&#39;, { name: /login/i });<br>    fireEvent.click(submitButton);<br><br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(/email is required/i)).toBeInTheDocument();<br>      expect(screen.getByText(/password is required/i)).toBeInTheDocument();<br>    });<br>  });<br><br>  it(&#39;should submit form with valid data&#39;, async () =&gt; {<br>    const mockLogin = jest.mocked(AuthService.login);<br>    mockLogin.mockResolvedValue({<br>      id: &#39;1&#39;,<br>      email: &#39;test@example.com&#39;,<br>      name: &#39;Test User&#39;,<br>      role: &#39;user&#39;,<br>    });<br><br>    render(&lt;LoginForm /&gt;, { wrapper: createWrapper() });<br>    <br>    const emailInput = screen.getByLabelText(/email/i);<br>    const passwordInput = screen.getByLabelText(/password/i);<br>    const submitButton = screen.getByRole(&#39;button&#39;, { name: /login/i });<br><br>    fireEvent.change(emailInput, { target: { value: &#39;test@example.com&#39; } });<br>    fireEvent.change(passwordInput, { target: { value: &#39;password123&#39; } });<br>    fireEvent.click(submitButton);<br><br>    await waitFor(() =&gt; {<br>      expect(mockLogin).toHaveBeenCalledWith({<br>        email: &#39;test@example.com&#39;,<br>        password: &#39;password123&#39;,<br>      });<br>    });<br>  });<br>});</pre><p><strong>Testing Components</strong>:</p><ul><li><strong>Unit Tests</strong>: Individual functions and components</li><li><strong>Integration Tests</strong>: Multiple components working together</li><li><strong>E2E Tests</strong>: Real user scenario validation</li></ul><h3>8. Performance Optimization</h3><h4>Memoization Strategy</h4><pre>// src/components/ProductList.tsx<br>import React, { useMemo } from &#39;react&#39;;<br>import { Product } from &#39;@/types/product&#39;;<br><br>interface ProductListProps {<br>  products: Product[];<br>  filter: string;<br>  sortBy: &#39;name&#39; | &#39;price&#39; | &#39;rating&#39;;<br>}<br><br>export const ProductList: React.FC&lt;ProductListProps&gt; = React.memo(({<br>  products,<br>  filter,<br>  sortBy,<br>}) =&gt; {<br>  const filteredAndSortedProducts = useMemo(() =&gt; {<br>    let filtered = products.filter(product =&gt;<br>      product.name.toLowerCase().includes(filter.toLowerCase())<br>    );<br><br>    return filtered.sort((a, b) =&gt; {<br>      switch (sortBy) {<br>        case &#39;name&#39;:<br>          return a.name.localeCompare(b.name);<br>        case &#39;price&#39;:<br>          return a.price - b.price;<br>        case &#39;rating&#39;:<br>          return b.rating - a.rating;<br>        default:<br>          return 0;<br>      }<br>    });<br>  }, [products, filter, sortBy]);<br><br>  return (<br>    &lt;div className=&quot;grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4&quot;&gt;<br>      {filteredAndSortedProducts.map(product =&gt; (<br>        &lt;ProductCard key={product.id} product={product} /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>});<br><br>ProductList.displayName = &#39;ProductList&#39;;</pre><h4>Virtualized Lists</h4><pre>// src/components/VirtualizedList.tsx<br>import { FixedSizeList as List } from &#39;react-window&#39;;<br><br>interface VirtualizedListProps&lt;T&gt; {<br>  items: T[];<br>  height: number;<br>  itemHeight: number;<br>  renderItem: (item: T, index: number) =&gt; React.ReactNode;<br>}<br><br>export function VirtualizedList&lt;T&gt;({<br>  items,<br>  height,<br>  itemHeight,<br>  renderItem,<br>}: VirtualizedListProps&lt;T&gt;) {<br>  const Row = ({ index, style }: { index: number; style: React.CSSProperties }) =&gt; (<br>    &lt;div style={style}&gt;<br>      {renderItem(items[index], index)}<br>    &lt;/div&gt;<br>  );<br><br>  return (<br>    &lt;List<br>      height={height}<br>      itemCount={items.length}<br>      itemSize={itemHeight}<br>    &gt;<br>      {Row}<br>    &lt;/List&gt;<br>  );<br>}</pre><p><strong>Performance Optimization Techniques</strong>:</p><ul><li><strong>React.memo</strong>: Prevent unnecessary re-renders</li><li><strong>useMemo/useCallback</strong>: Optimize expensive calculations</li><li><strong>Code Splitting</strong>: Reduce initial loading time</li><li><strong>Virtualization</strong>: Efficient rendering of large datasets</li></ul><h3>9. Security Considerations</h3><pre>// src/utils/security.ts<br>/**<br> * Escapes HTML to prevent XSS attacks<br> */<br>export function escapeHtml(text: string): string {<br>  const div = document.createElement(&#39;div&#39;);<br>  div.textContent = text;<br>  return div.innerHTML;<br>}<br><br>/**<br> * Sanitizes sensitive information from logs<br> */<br>export function sanitizeLogData(data: any): any {<br>  const sensitiveKeys = [&#39;password&#39;, &#39;token&#39;, &#39;secret&#39;, &#39;key&#39;];<br>  <br>  if (typeof data !== &#39;object&#39; || data === null) {<br>    return data;<br>  }<br><br>  const sanitized = { ...data };<br>  <br>  for (const key in sanitized) {<br>    if (sensitiveKeys.some(sensitive =&gt; <br>      key.toLowerCase().includes(sensitive)<br>    )) {<br>      sanitized[key] = &#39;[REDACTED]&#39;;<br>    } else if (typeof sanitized[key] === &#39;object&#39;) {<br>      sanitized[key] = sanitizeLogData(sanitized[key]);<br>    }<br>  }<br><br>  return sanitized;<br>}</pre><h3>10. Deployment Optimization</h3><pre>// vite.config.ts<br>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br>import { resolve } from &#39;path&#39;;<br><br>export default defineConfig({<br>  plugins: [react()],<br>  resolve: {<br>    alias: {<br>      &#39;@&#39;: resolve(__dirname, &#39;src&#39;),<br>    },<br>  },<br>  build: {<br>    rollupOptions: {<br>      output: {<br>        manualChunks: {<br>          vendor: [&#39;react&#39;, &#39;react-dom&#39;],<br>          ui: [&#39;@headlessui/react&#39;, &#39;@heroicons/react&#39;],<br>          utils: [&#39;lodash&#39;, &#39;date-fns&#39;],<br>        },<br>      },<br>    },<br>  },<br>});</pre><h3>11. Conclusion</h3><p>These architectural patterns provide several key benefits for large-scale React applications:</p><h4>Key Advantages</h4><ol><li><strong>Scalability</strong>: Minimal impact on existing code when adding new features</li><li><strong>Maintainability</strong>: Clear structure improves code comprehension</li><li><strong>Reusability</strong>: Common components and hooks eliminate code duplication</li><li><strong>Testability</strong>: Separation of concerns makes testing easier</li><li><strong>Team Collaboration</strong>: Consistent structure improves team efficiency</li></ol><h4>Next Steps</h4><ul><li><strong>Monitoring</strong>: Error tracking with Sentry, LogRocket</li><li><strong>Performance Measurement</strong>: Web Vitals, Lighthouse monitoring</li><li><strong>Automation</strong>: CI/CD pipeline setup</li><li><strong>Documentation</strong>: Component documentation with Storybook</li></ul><p>Building large-scale React applications isn’t just about writing code — it’s about <strong>creating sustainable development environments</strong>. Apply these architectural patterns to your projects and create better developer experiences that scale with your team and product needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eac48a4406f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React GraphQL Integration: The Complete Apollo Client Guide]]></title>
            <link>https://medium.com/@dlrnjstjs/react-graphql-integration-the-complete-apollo-client-guide-01429593500c?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/01429593500c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 02:50:40 GMT</pubDate>
            <atom:updated>2025-09-24T02:50:40.217Z</atom:updated>
            <content:encoded><![CDATA[<p>GraphQL has revolutionized how we think about API development, offering a more efficient and flexible alternative to REST APIs. When combined with React and Apollo Client, it creates a powerful stack for building modern web applications. This comprehensive guide will walk you through everything you need to know about integrating GraphQL with React using Apollo Client.</p><h3>Table of Contents</h3><ol><li>Introduction to GraphQL and Apollo Client</li><li>Project Setup and Installation</li><li>Apollo Client Configuration</li><li>Implementing Queries</li><li>Implementing Mutations</li><li>Caching and State Management</li><li>Advanced Features</li><li>Best Practices and Production Tips</li></ol><h3>1. Introduction to GraphQL and Apollo Client</h3><h4>What is GraphQL?</h4><p>GraphQL is a query language and runtime for APIs developed by Facebook (now Meta). Unlike REST APIs, GraphQL allows clients to request exactly the data they need, making it more efficient and flexible.</p><p><strong>Key advantages of GraphQL:</strong></p><ul><li>Single endpoint for all data operations</li><li>Client-specified data fetching</li><li>Strong type system</li><li>Real-time subscriptions support</li><li>Introspection capabilities</li></ul><h4>What is Apollo Client?</h4><p>Apollo Client is a comprehensive state management library for GraphQL. It provides seamless integration with React and handles caching, error management, loading states, and much more automatically.</p><p><strong>Apollo Client features:</strong></p><ul><li>Intelligent caching system</li><li>Optimistic UI updates</li><li>Error handling and retry logic</li><li>DevTools integration</li><li>TypeScript support</li></ul><h3>2. Project Setup and Installation</h3><h4>Creating a New React Project</h4><pre>npx create-react-app my-graphql-app<br>cd my-graphql-app</pre><h4>Installing Required Packages</h4><pre>npm install @apollo/client graphql</pre><p><strong>Package descriptions:</strong></p><ul><li>@apollo/client: Core Apollo Client library</li><li>graphql: JavaScript implementation of GraphQL</li></ul><h4>Installing Development Dependencies (Optional)</h4><pre>npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript</pre><h3>3. Apollo Client Configuration</h3><h4>3.1 Creating Apollo Client Instance</h4><p>Create src/apollo/client.js and configure as follows:</p><pre>import { ApolloClient, InMemoryCache, createHttpLink } from &#39;@apollo/client&#39;;<br>import { setContext } from &#39;@apollo/client/link/context&#39;;<br><br>// GraphQL endpoint configuration<br>const httpLink = createHttpLink({<br>  uri: &#39;https://api.example.com/graphql&#39;, // Your GraphQL server URL<br>});<br><br>// Authentication header setup (JWT tokens, etc.)<br>const authLink = setContext((_, { headers }) =&gt; {<br>  // Get token from localStorage<br>  const token = localStorage.getItem(&#39;token&#39;);<br>  <br>  return {<br>    headers: {<br>      ...headers,<br>      authorization: token ? `Bearer ${token}` : &quot;&quot;,<br>    }<br>  }<br>});<br><br>// Create Apollo Client instance<br>const client = new ApolloClient({<br>  // Link chain: authentication -&gt; HTTP request<br>  link: authLink.concat(httpLink),<br>  <br>  // Cache configuration<br>  cache: new InMemoryCache({<br>    typePolicies: {<br>      // Cache policy configuration (optional)<br>      Query: {<br>        fields: {<br>          posts: {<br>            // Cache merge policy for pagination<br>            keyArgs: false,<br>            merge(existing = [], incoming) {<br>              return [...existing, ...incoming];<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }),<br>  <br>  // Connect to Apollo DevTools in development<br>  connectToDevTools: process.env.NODE_ENV === &#39;development&#39;,<br>});<br><br>export default client;</pre><p><strong>Detailed code explanation:</strong></p><ul><li><strong>httpLink</strong>: Handles HTTP connections to the GraphQL server</li><li><strong>authLink</strong>: Automatically adds authentication headers to all requests</li><li><strong>InMemoryCache</strong>: Caches query results in memory for performance optimization</li><li><strong>typePolicies</strong>: Allows fine-grained control over cache behavior for specific types</li></ul><h4>3.2 Connecting Apollo Provider to React App</h4><p>Configure Apollo Provider in src/index.js:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import { ApolloProvider } from &#39;@apollo/client&#39;;<br>import client from &#39;./apollo/client&#39;;<br>import App from &#39;./App&#39;;<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br><br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;ApolloProvider client={client}&gt;<br>      &lt;App /&gt;<br>    &lt;/ApolloProvider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p><strong>ApolloProvider</strong> uses React Context API to make the Apollo Client instance accessible throughout the entire application.</p><h3>4. Implementing Queries</h3><h4>4.1 Defining GraphQL Queries</h4><p>Create src/graphql/queries.js:</p><pre>import { gql } from &#39;@apollo/client&#39;;<br><br>// User list query<br>export const GET_USERS = gql`<br>  query GetUsers($first: Int, $after: String) {<br>    users(first: $first, after: $after) {<br>      edges {<br>        node {<br>          id<br>          name<br>          email<br>          avatar<br>          createdAt<br>        }<br>        cursor<br>      }<br>      pageInfo {<br>        hasNextPage<br>        endCursor<br>      }<br>    }<br>  }<br>`;<br><br>// Specific user detail query<br>export const GET_USER = gql`<br>  query GetUser($id: ID!) {<br>    user(id: $id) {<br>      id<br>      name<br>      email<br>      avatar<br>      bio<br>      posts {<br>        id<br>        title<br>        content<br>        createdAt<br>      }<br>    }<br>  }<br>`;</pre><p>The <strong>gql tag</strong> parses GraphQL query strings into a format that Apollo Client can understand.</p><h4>4.2 Using useQuery Hook</h4><p>Here’s how to execute queries in React components:</p><pre>import React from &#39;react&#39;;<br>import { useQuery } from &#39;@apollo/client&#39;;<br>import { GET_USERS } from &#39;../graphql/queries&#39;;<br><br>const UserList = () =&gt; {<br>  // Execute query with useQuery hook<br>  const { loading, error, data, refetch, fetchMore } = useQuery(GET_USERS, {<br>    variables: {<br>      first: 10, // Fetch 10 users initially<br>    },<br>    // Query options<br>    errorPolicy: &#39;all&#39;, // Show partial data even with errors<br>    fetchPolicy: &#39;cache-and-network&#39;, // Cache first, then network update<br>    notifyOnNetworkStatusChange: true, // Re-render on network status changes<br>  });<br><br>  // Handle loading state<br>  if (loading &amp;&amp; !data) {<br>    return (<br>      &lt;div className=&quot;flex justify-center items-center h-64&quot;&gt;<br>        &lt;div className=&quot;animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500&quot;&gt;&lt;/div&gt;<br>        &lt;span className=&quot;ml-2&quot;&gt;Loading users...&lt;/span&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  // Handle error state<br>  if (error) {<br>    return (<br>      &lt;div className=&quot;bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded&quot;&gt;<br>        &lt;strong&gt;Error occurred:&lt;/strong&gt; {error.message}<br>        &lt;button <br>          onClick={() =&gt; refetch()}<br>          className=&quot;ml-2 bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded text-sm&quot;<br>        &gt;<br>          Retry<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  const users = data?.users?.edges || [];<br><br>  // Load more data function<br>  const loadMore = () =&gt; {<br>    if (data.users.pageInfo.hasNextPage) {<br>      fetchMore({<br>        variables: {<br>          after: data.users.pageInfo.endCursor,<br>        },<br>      });<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;container mx-auto px-4&quot;&gt;<br>      &lt;h1 className=&quot;text-2xl font-bold mb-6&quot;&gt;User List&lt;/h1&gt;<br>      <br>      {/* User card list */}<br>      &lt;div className=&quot;grid gap-4 md:grid-cols-2 lg:grid-cols-3&quot;&gt;<br>        {users.map(({ node: user }) =&gt; (<br>          &lt;div key={user.id} className=&quot;bg-white shadow rounded-lg p-4&quot;&gt;<br>            &lt;div className=&quot;flex items-center space-x-3&quot;&gt;<br>              &lt;img<br>                src={user.avatar || &#39;/default-avatar.png&#39;}<br>                alt={user.name}<br>                className=&quot;w-12 h-12 rounded-full object-cover&quot;<br>              /&gt;<br>              &lt;div&gt;<br>                &lt;h3 className=&quot;font-semibold&quot;&gt;{user.name}&lt;/h3&gt;<br>                &lt;p className=&quot;text-gray-600 text-sm&quot;&gt;{user.email}&lt;/p&gt;<br>                &lt;p className=&quot;text-gray-500 text-xs&quot;&gt;<br>                  Joined: {new Date(user.createdAt).toLocaleDateString()}<br>                &lt;/p&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br><br>      {/* Load more button */}<br>      {data.users.pageInfo.hasNextPage &amp;&amp; (<br>        &lt;div className=&quot;text-center mt-6&quot;&gt;<br>          &lt;button<br>            onClick={loadMore}<br>            disabled={loading}<br>            className=&quot;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50&quot;<br>          &gt;<br>            {loading ? &#39;Loading...&#39; : &#39;Load More&#39;}<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UserList;</pre><p><strong>Key useQuery hook return values:</strong></p><ul><li><strong>loading</strong>: Whether the query is currently executing</li><li><strong>error</strong>: Error object (if an error occurred)</li><li><strong>data</strong>: Query result data</li><li><strong>refetch</strong>: Function to re-execute the query</li><li><strong>fetchMore</strong>: Function to load additional data (for pagination)</li></ul><h4>4.3 Conditional Query Execution</h4><p>When you want to execute queries only under certain conditions:</p><pre>const UserDetail = ({ userId }) =&gt; {<br>  const { loading, error, data } = useQuery(GET_USER, {<br>    variables: { id: userId },<br>    skip: !userId, // Don&#39;t execute query if userId is not available<br>    onCompleted: (data) =&gt; {<br>      console.log(&#39;User data loaded:&#39;, data);<br>    },<br>    onError: (error) =&gt; {<br>      console.error(&#39;Query error:&#39;, error);<br>    }<br>  });<br><br>  if (!userId) {<br>    return &lt;div&gt;Please select a user.&lt;/div&gt;;<br>  }<br><br>  // Rest of rendering logic...<br>};</pre><h3>5. Implementing Mutations</h3><h4>5.1 Defining GraphQL Mutations</h4><p>Create src/graphql/mutations.js:</p><pre>import { gql } from &#39;@apollo/client&#39;;<br><br>// User creation mutation<br>export const CREATE_USER = gql`<br>  mutation CreateUser($input: CreateUserInput!) {<br>    createUser(input: $input) {<br>      user {<br>        id<br>        name<br>        email<br>        avatar<br>        createdAt<br>      }<br>      errors {<br>        field<br>        message<br>      }<br>    }<br>  }<br>`;<br><br>// User update mutation<br>export const UPDATE_USER = gql`<br>  mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {<br>    updateUser(id: $id, input: $input) {<br>      user {<br>        id<br>        name<br>        email<br>        bio<br>        avatar<br>      }<br>      errors {<br>        field<br>        message<br>      }<br>    }<br>  }<br>`;<br><br>// User deletion mutation<br>export const DELETE_USER = gql`<br>  mutation DeleteUser($id: ID!) {<br>    deleteUser(id: $id) {<br>      success<br>      message<br>    }<br>  }<br>`;</pre><h4>5.2 Using useMutation Hook</h4><p>Here’s an example of user creation using a form:</p><pre>import React, { useState } from &#39;react&#39;;<br>import { useMutation } from &#39;@apollo/client&#39;;<br>import { CREATE_USER } from &#39;../graphql/mutations&#39;;<br>import { GET_USERS } from &#39;../graphql/queries&#39;;<br><br>const CreateUserForm = ({ onSuccess }) =&gt; {<br>  const [formData, setFormData] = useState({<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    bio: &#39;&#39;,<br>  });<br><br>  // Use useMutation hook<br>  const [createUser, { loading, error, data }] = useMutation(CREATE_USER, {<br>    // Update cache on success<br>    update(cache, { data }) {<br>      if (data.createUser.user) {<br>        // Add new user to existing user list<br>        const existingUsers = cache.readQuery({ query: GET_USERS });<br>        <br>        if (existingUsers) {<br>          cache.writeQuery({<br>            query: GET_USERS,<br>            data: {<br>              users: {<br>                ...existingUsers.users,<br>                edges: [<br>                  {<br>                    node: data.createUser.user,<br>                    cursor: data.createUser.user.id,<br>                    __typename: &#39;UserEdge&#39;<br>                  },<br>                  ...existingUsers.users.edges,<br>                ]<br>              }<br>            }<br>          });<br>        }<br>      }<br>    },<br>    <br>    // Completion callback<br>    onCompleted: (data) =&gt; {<br>      if (data.createUser.user) {<br>        setFormData({ name: &#39;&#39;, email: &#39;&#39;, bio: &#39;&#39; }); // Reset form<br>        onSuccess?.(data.createUser.user);<br>      }<br>    },<br>    <br>    // Error callback<br>    onError: (error) =&gt; {<br>      console.error(&#39;User creation error:&#39;, error);<br>    }<br>  });<br><br>  // Form input handler<br>  const handleChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setFormData(prev =&gt; ({<br>      ...prev,<br>      [name]: value<br>    }));<br>  };<br><br>  // Form submission handler<br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    <br>    // Validation<br>    if (!formData.name.trim() || !formData.email.trim()) {<br>      alert(&#39;Please enter name and email.&#39;);<br>      return;<br>    }<br><br>    try {<br>      await createUser({<br>        variables: {<br>          input: {<br>            name: formData.name.trim(),<br>            email: formData.email.trim(),<br>            bio: formData.bio.trim(),<br>          }<br>        }<br>      });<br>    } catch (err) {<br>      // Error handled by onError callback<br>      console.error(&#39;Mutation execution error:&#39;, err);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit} className=&quot;max-w-md mx-auto bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4&quot;&gt;<br>      &lt;h2 className=&quot;text-xl font-bold mb-4&quot;&gt;Add New User&lt;/h2&gt;<br>      <br>      {/* Name input */}<br>      &lt;div className=&quot;mb-4&quot;&gt;<br>        &lt;label className=&quot;block text-gray-700 text-sm font-bold mb-2&quot;&gt;<br>          Name *<br>        &lt;/label&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          name=&quot;name&quot;<br>          value={formData.name}<br>          onChange={handleChange}<br>          className=&quot;shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline&quot;<br>          placeholder=&quot;Enter user name&quot;<br>          disabled={loading}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      {/* Email input */}<br>      &lt;div className=&quot;mb-4&quot;&gt;<br>        &lt;label className=&quot;block text-gray-700 text-sm font-bold mb-2&quot;&gt;<br>          Email *<br>        &lt;/label&gt;<br>        &lt;input<br>          type=&quot;email&quot;<br>          name=&quot;email&quot;<br>          value={formData.email}<br>          onChange={handleChange}<br>          className=&quot;shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline&quot;<br>          placeholder=&quot;Enter email address&quot;<br>          disabled={loading}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      {/* Bio input */}<br>      &lt;div className=&quot;mb-6&quot;&gt;<br>        &lt;label className=&quot;block text-gray-700 text-sm font-bold mb-2&quot;&gt;<br>          Bio<br>        &lt;/label&gt;<br>        &lt;textarea<br>          name=&quot;bio&quot;<br>          value={formData.bio}<br>          onChange={handleChange}<br>          rows=&quot;3&quot;<br>          className=&quot;shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline&quot;<br>          placeholder=&quot;Enter bio (optional)&quot;<br>          disabled={loading}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      {/* Server error display */}<br>      {data?.createUser?.errors &amp;&amp; (<br>        &lt;div className=&quot;mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded&quot;&gt;<br>          {data.createUser.errors.map((error, index) =&gt; (<br>            &lt;div key={index}&gt;<br>              &lt;strong&gt;{error.field}:&lt;/strong&gt; {error.message}<br>            &lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      )}<br><br>      {/* GraphQL error display */}<br>      {error &amp;&amp; (<br>        &lt;div className=&quot;mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded&quot;&gt;<br>          Error: {error.message}<br>        &lt;/div&gt;<br>      )}<br><br>      {/* Submit button */}<br>      &lt;div className=&quot;flex items-center justify-between&quot;&gt;<br>        &lt;button<br>          type=&quot;submit&quot;<br>          disabled={loading}<br>          className=&quot;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline disabled:opacity-50&quot;<br>        &gt;<br>          {loading ? &#39;Creating...&#39; : &#39;Create User&#39;}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default CreateUserForm;</pre><p><strong>Key useMutation features:</strong></p><ul><li><strong>update</strong>: Manually update cache after successful mutation</li><li><strong>onCompleted</strong>: Callback function executed on success</li><li><strong>onError</strong>: Callback function executed on error</li><li><strong>refetchQueries</strong>: List of queries to re-execute after mutation</li></ul><h4>5.3 Optimistic Updates</h4><p>For improved user experience, you can implement optimistic updates:</p><pre>const [updateUser] = useMutation(UPDATE_USER, {<br>  // Optimistic update: Update UI before server response<br>  optimisticResponse: {<br>    updateUser: {<br>      __typename: &#39;UpdateUserPayload&#39;,<br>      user: {<br>        __typename: &#39;User&#39;,<br>        id: userId,<br>        name: newName,<br>        email: newEmail,<br>        bio: newBio,<br>      },<br>      errors: null,<br>    },<br>  },<br>  <br>  update(cache, { data }) {<br>    // Update cache with actual server response<br>    if (data.updateUser.user) {<br>      cache.modify({<br>        id: cache.identify(data.updateUser.user),<br>        fields: {<br>          name: () =&gt; data.updateUser.user.name,<br>          email: () =&gt; data.updateUser.user.email,<br>          bio: () =&gt; data.updateUser.user.bio,<br>        }<br>      });<br>    }<br>  }<br>});</pre><h3>6. Caching and State Management</h3><h4>6.1 Understanding Apollo Cache</h4><p>Apollo Client uses a normalized cache. Each object is uniquely identified based on __typename and id fields.</p><pre>// Read specific object from cache<br>const user = cache.readFragment({<br>  id: &#39;User:123&#39;,<br>  fragment: gql`<br>    fragment UserInfo on User {<br>      id<br>      name<br>      email<br>    }<br>  `<br>});<br><br>// Modify specific fields in cache<br>cache.modify({<br>  id: &#39;User:123&#39;,<br>  fields: {<br>    name: (existingName) =&gt; newName,<br>    email: (existingEmail) =&gt; newEmail,<br>  }<br>});</pre><h4>6.2 Local State Management</h4><p>Apollo Client can manage both server data and client local state:</p><pre>// Local type definitions<br>const typeDefs = gql`<br>  extend type Query {<br>    isLoggedIn: Boolean!<br>    cartItems: [ID!]!<br>  }<br>`;<br><br>// Local resolver functions<br>const resolvers = {<br>  Query: {<br>    isLoggedIn: () =&gt; {<br>      return !!localStorage.getItem(&#39;token&#39;);<br>    },<br>    cartItems: () =&gt; {<br>      const items = localStorage.getItem(&#39;cartItems&#39;);<br>      return items ? JSON.parse(items) : [];<br>    },<br>  },<br>};<br><br>// Add local configuration to Apollo Client<br>const client = new ApolloClient({<br>  uri: &#39;https://api.example.com/graphql&#39;,<br>  cache: new InMemoryCache(),<br>  typeDefs,<br>  resolvers,<br>});<br><br>// Use local state in components<br>const GET_LOCAL_STATE = gql`<br>  query GetLocalState {<br>    isLoggedIn @client<br>    cartItems @client<br>  }<br>`;<br><br>const Header = () =&gt; {<br>  const { data } = useQuery(GET_LOCAL_STATE);<br>  <br>  return (<br>    &lt;header&gt;<br>      {data.isLoggedIn ? (<br>        &lt;div&gt;Logged in - Cart: {data.cartItems.length} items&lt;/div&gt;<br>      ) : (<br>        &lt;div&gt;Please log in&lt;/div&gt;<br>      )}<br>    &lt;/header&gt;<br>  );<br>};</pre><h3>7. Advanced Features</h3><h4>7.1 Real-time Subscriptions</h4><p>Real-time data subscriptions via WebSocket:</p><pre>import { GraphQLWsLink } from &#39;@apollo/client/link/subscriptions&#39;;<br>import { createClient } from &#39;graphql-ws&#39;;<br><br>// Create WebSocket link<br>const wsLink = new GraphQLWsLink(<br>  createClient({<br>    url: &#39;ws://localhost:4000/subscriptions&#39;,<br>  })<br>);<br><br>// Split HTTP and WebSocket links<br>import { split } from &#39;@apollo/client&#39;;<br>import { getMainDefinition } from &#39;@apollo/client/utilities&#39;;<br><br>const splitLink = split(<br>  ({ query }) =&gt; {<br>    const definition = getMainDefinition(query);<br>    return (<br>      definition.kind === &#39;OperationDefinition&#39; &amp;&amp;<br>      definition.operation === &#39;subscription&#39;<br>    );<br>  },<br>  wsLink,  // Subscriptions via WebSocket<br>  httpLink // Queries/mutations via HTTP<br>);<br><br>// Subscription query definition<br>const MESSAGE_SUBSCRIPTION = gql`<br>  subscription OnMessageAdded($chatId: ID!) {<br>    messageAdded(chatId: $chatId) {<br>      id<br>      content<br>      user {<br>        id<br>        name<br>      }<br>      createdAt<br>    }<br>  }<br>`;<br><br>// Use subscription in component<br>const ChatRoom = ({ chatId }) =&gt; {<br>  const { data, loading } = useSubscription(MESSAGE_SUBSCRIPTION, {<br>    variables: { chatId },<br>    onSubscriptionData: ({ subscriptionData }) =&gt; {<br>      // Handle new message arrival<br>      console.log(&#39;New message:&#39;, subscriptionData.data.messageAdded);<br>    }<br>  });<br><br>  // Rendering logic...<br>};</pre><h4>7.2 Error Handling Strategies</h4><p>Global error handling setup:</p><pre>import { onError } from &#39;@apollo/client/link/error&#39;;<br><br>const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) =&gt; {<br>  if (graphQLErrors) {<br>    graphQLErrors.forEach(({ message, locations, path }) =&gt; {<br>      console.error(<br>        `GraphQL error: Message: ${message}, Location: ${locations}, Path: ${path}`<br>      );<br>    });<br>  }<br><br>  if (networkError) {<br>    console.error(`Network error: ${networkError}`);<br>    <br>    // Handle 401 Unauthorized - logout user<br>    if (networkError.statusCode === 401) {<br>      localStorage.removeItem(&#39;token&#39;);<br>      window.location.href = &#39;/login&#39;;<br>    }<br>  }<br>});<br><br>// Add error link to client<br>const client = new ApolloClient({<br>  link: from([errorLink, authLink, httpLink]),<br>  cache: new InMemoryCache(),<br>});</pre><h4>7.3 Performance Optimization</h4><h4>Query Splitting and Lazy Loading</h4><pre>import { useLazyQuery } from &#39;@apollo/client&#39;;<br><br>const SearchComponent = () =&gt; {<br>  const [searchUsers, { loading, data, error }] = useLazyQuery(SEARCH_USERS, {<br>    fetchPolicy: &#39;cache-and-network&#39;<br>  });<br><br>  const handleSearch = (searchTerm) =&gt; {<br>    if (searchTerm.trim().length &gt; 2) {<br>      searchUsers({<br>        variables: { query: searchTerm }<br>      });<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        onChange={(e) =&gt; handleSearch(e.target.value)}<br>        placeholder=&quot;Search users...&quot;<br>      /&gt;<br>      {loading &amp;&amp; &lt;div&gt;Searching...&lt;/div&gt;}<br>      {data &amp;&amp; (<br>        &lt;div&gt;<br>          {data.searchUsers.map(user =&gt; (<br>            &lt;div key={user.id}&gt;{user.name}&lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>Field-level Cache Policies</h4><pre>const cache = new InMemoryCache({<br>  typePolicies: {<br>    Product: {<br>      fields: {<br>        reviews: {<br>          merge(existing = [], incoming) {<br>            return [...existing, ...incoming];<br>          }<br>        }<br>      }<br>    },<br>    User: {<br>      fields: {<br>        posts: relayStylePagination(), // Relay-style pagination<br>      }<br>    }<br>  }<br>});</pre><h3>8. Best Practices and Production Tips</h3><h4>8.1 Query Optimization</h4><ol><li><strong>Request Only Necessary Fields</strong></li></ol><pre>// ❌ Bad: Requesting unnecessary fields<br>const GET_USERS_BAD = gql`<br>  query GetUsers {<br>    users {<br>      id<br>      name<br>      email<br>      bio<br>      avatar<br>      posts {<br>        id<br>        title<br>        content<br>        createdAt<br>        updatedAt<br>        comments {<br>          id<br>          content<br>          author {<br>            id<br>            name<br>          }<br>        }<br>      }<br>    }<br>  }<br>`;<br><br>// ✅ Good: Request only needed fields<br>const GET_USERS_GOOD = gql`<br>  query GetUsers {<br>    users {<br>      id<br>      name<br>      email<br>      avatar<br>    }<br>  }<br>`;</pre><h4>2. Utilize Fragments</h4><pre>// Define common fields as fragments<br>const USER_FRAGMENT = gql`<br>  fragment UserInfo on User {<br>    id<br>    name<br>    email<br>    avatar<br>    createdAt<br>  }<br>`;<br><br>// Reuse fragments<br>const GET_USERS = gql`<br>  query GetUsers {<br>    users {<br>      ...UserInfo<br>    }<br>  }<br>  ${USER_FRAGMENT}<br>`;<br><br>const GET_USER_DETAIL = gql`<br>  query GetUserDetail($id: ID!) {<br>    user(id: $id) {<br>      ...UserInfo<br>      bio<br>      posts {<br>        id<br>        title<br>        content<br>      }<br>    }<br>  }<br>  ${USER_FRAGMENT}<br>`;</pre><h4>8.2 Error Handling Patterns</h4><ol><li><strong>Component-level Error Boundaries</strong></li></ol><pre>import React from &#39;react&#39;;<br><br>class GraphQLErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { hasError: false };<br>  }<br><br>  static getDerivedStateFromError(error) {<br>    return { hasError: true };<br>  }<br><br>  componentDidCatch(error, errorInfo) {<br>    console.error(&#39;GraphQL Error Boundary:&#39;, error, errorInfo);<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      return (<br>        &lt;div className=&quot;error-fallback&quot;&gt;<br>          &lt;h2&gt;Something went wrong&lt;/h2&gt;<br>          &lt;button onClick={() =&gt; window.location.reload()}&gt;<br>            Reload Page<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      );<br>    }<br><br>    return this.props.children;<br>  }<br>}<br><br>// Usage<br>const App = () =&gt; (<br>  &lt;GraphQLErrorBoundary&gt;<br>    &lt;UserList /&gt;<br>  &lt;/GraphQLErrorBoundary&gt;<br>);</pre><h4>2. Retry Logic</h4><pre>import { RetryLink } from &#39;@apollo/client/link/retry&#39;;<br><br>const retryLink = new RetryLink({<br>  delay: {<br>    initial: 300,<br>    max: Infinity,<br>    jitter: true<br>  },<br>  attempts: {<br>    max: 5,<br>    retryIf: (error, _operation) =&gt; {<br>      return !!error &amp;&amp; error.networkError?.statusCode &gt;= 500;<br>    }<br>  }<br>});</pre><h4>8.3 Type Safety Enhancement</h4><p><strong>1. GraphQL Code Generator Setup</strong></p><p>Create codegen.yml:</p><pre>overwrite: true<br>schema: &quot;https://api.example.com/graphql&quot;<br>documents: &quot;src/**/*.{ts,tsx,js,jsx,graphql}&quot;<br>generates:<br>  src/generated/graphql.tsx:<br>    plugins:<br>      - &quot;typescript&quot;<br>      - &quot;typescript-operations&quot;<br>      - &quot;typescript-react-apollo&quot;<br>    config:<br>      withHooks: true<br>      withComponent: false<br>      withHOC: false</pre><p><strong>2. Using Generated Types</strong></p><pre>import { useGetUsersQuery, User } from &#39;../generated/graphql&#39;;<br><br>const UserList: React.FC = () =&gt; {<br>  const { data, loading, error } = useGetUsersQuery({<br>    variables: {<br>      first: 10<br>    }<br>  });<br><br>  // TypeScript automatically infers types<br>  const users: User[] = data?.users?.edges?.map(edge =&gt; edge.node) || [];<br><br>  return (<br>    &lt;div&gt;<br>      {users.map(user =&gt; (<br>        &lt;UserCard key={user.id} user={user} /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>8.4 Testing Strategies</h4><ol><li><strong>Testing with MockedProvider</strong></li></ol><pre>import { MockedProvider } from &#39;@apollo/client/testing&#39;;<br>import { render, screen } from &#39;@testing-library/react&#39;;<br>import UserList from &#39;../UserList&#39;;<br>import { GET_USERS } from &#39;../graphql/queries&#39;;<br><br>const mocks = [<br>  {<br>    request: {<br>      query: GET_USERS,<br>      variables: {<br>        first: 10,<br>      },<br>    },<br>    result: {<br>      data: {<br>        users: {<br>          edges: [<br>            {<br>              node: {<br>                id: &#39;1&#39;,<br>                name: &#39;John Doe&#39;,<br>                email: &#39;john@example.com&#39;,<br>                avatar: null,<br>                createdAt: &#39;2023-01-01T00:00:00Z&#39;,<br>              },<br>              cursor: &#39;1&#39;,<br>            },<br>          ],<br>          pageInfo: {<br>            hasNextPage: false,<br>            endCursor: &#39;1&#39;,<br>          },<br>        },<br>      },<br>    },<br>  },<br>];<br><br>test(&#39;renders user list correctly&#39;, async () =&gt; {<br>  render(<br>    &lt;MockedProvider mocks={mocks} addTypename={false}&gt;<br>      &lt;UserList /&gt;<br>    &lt;/MockedProvider&gt;<br>  );<br><br>  // Check loading state<br>  expect(screen.getByText(&#39;Loading users...&#39;)).toBeInTheDocument();<br><br>  // Check data after loading<br>  await screen.findByText(&#39;John Doe&#39;);<br>  expect(screen.getByText(&#39;john@example.com&#39;)).toBeInTheDocument();<br>});</pre><p><strong>2. Testing Error Scenarios</strong></p><pre>const errorMocks = [<br>  {<br>    request: {<br>      query: GET_USERS,<br>      variables: { first: 10 },<br>    },<br>    error: new Error(&#39;Network error occurred&#39;),<br>  },<br>];<br><br>test(&#39;handles error scenarios correctly&#39;, async () =&gt; {<br>  render(<br>    &lt;MockedProvider mocks={errorMocks} addTypename={false}&gt;<br>      &lt;UserList /&gt;<br>    &lt;/MockedProvider&gt;<br>  );<br><br>  await screen.findByText(/Error occurred: Network error occurred/);<br>  expect(screen.getByText(&#39;Retry&#39;)).toBeInTheDocument();<br>});</pre><h4>8.5 Performance Monitoring</h4><ol><li><strong>Utilizing Apollo Client DevTools</strong></li></ol><pre>const client = new ApolloClient({<br>  uri: &#39;https://api.example.com/graphql&#39;,<br>  cache: new InMemoryCache(),<br>  connectToDevTools: true, // Connect DevTools<br>  defaultOptions: {<br>    watchQuery: {<br>      errorPolicy: &#39;all&#39;,<br>    },<br>    query: {<br>      errorPolicy: &#39;all&#39;,<br>    },<br>  },<br>});</pre><p><strong>2. Query Performance Measurement</strong></p><pre>const GET_USERS_WITH_TIMING = gql`<br>  query GetUsers($first: Int) {<br>    users(first: $first) @cached(ttl: 300) {<br>      edges {<br>        node {<br>          ...UserInfo<br>        }<br>      }<br>    }<br>  }<br>  ${USER_FRAGMENT}<br>`;<br><br>const UserList = () =&gt; {<br>  const { data, loading, error } = useQuery(GET_USERS_WITH_TIMING, {<br>    variables: { first: 10 },<br>    onCompleted: (data) =&gt; {<br>      console.log(&#39;Query completed at:&#39;, performance.now());<br>    },<br>    onError: (error) =&gt; {<br>      console.error(&#39;Query error:&#39;, error);<br>    }<br>  });<br><br>  // Component logic...<br>};</pre><h4>8.6 Production Deployment Considerations</h4><ol><li><strong>Environment Configuration</strong></li></ol><pre>const client = new ApolloClient({<br>  uri: process.env.REACT_APP_GRAPHQL_ENDPOINT || &#39;http://localhost:4000/graphql&#39;,<br>  cache: new InMemoryCache(),<br>  connectToDevTools: process.env.NODE_ENV === &#39;development&#39;,<br>  defaultOptions: {<br>    watchQuery: {<br>      fetchPolicy: process.env.NODE_ENV === &#39;production&#39; ? &#39;cache-first&#39; : &#39;cache-and-network&#39;,<br>    },<br>  },<br>});</pre><p><strong>2. Security Best Practices</strong></p><pre>// CSRF protection<br>const httpLink = createHttpLink({<br>  uri: &#39;https://api.example.com/graphql&#39;,<br>  credentials: &#39;include&#39;, // Include cookies for authentication<br>});<br><br>// Rate limiting consideration<br>const retryLink = new RetryLink({<br>  delay: {<br>    initial: 1000, // Longer delays in production<br>    max: 30000,<br>    jitter: true<br>  },<br>  attempts: {<br>    max: 3, // Fewer retries in production<br>    retryIf: (error) =&gt; !!error &amp;&amp; error.networkError?.statusCode &gt;= 500,<br>  }<br>});</pre><p><strong>3. Bundle Optimization</strong></p><pre>// Import only what you need<br>import { useQuery, useMutation } from &#39;@apollo/client&#39;;<br>// Instead of: import { ApolloClient } from &#39;@apollo/client&#39;;<br><br>// Use dynamic imports for large components<br>const UserDetailModal = React.lazy(() =&gt; import(&#39;./UserDetailModal&#39;));<br><br>const UserList = () =&gt; {<br>  const [showDetail, setShowDetail] = useState(false);<br>  <br>  return (<br>    &lt;div&gt;<br>      {/* User list */}<br>      {showDetail &amp;&amp; (<br>        &lt;React.Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>          &lt;UserDetailModal /&gt;<br>        &lt;/React.Suspense&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Conclusion</h3><p>Apollo Client provides a powerful and comprehensive solution for integrating GraphQL with React applications. Throughout this guide, we’ve covered the essential concepts and advanced techniques needed to build production-ready applications.</p><h4>Key Takeaways</h4><ol><li><strong>Proper Setup</strong>: Correct Apollo Client configuration significantly impacts overall application performance</li><li><strong>Caching Strategy</strong>: Appropriate caching policies minimize network requests and improve user experience</li><li><strong>Error Handling</strong>: Systematic error handling creates stable and reliable applications</li><li><strong>Type Safety</strong>: TypeScript and Code Generator enhance development productivity</li><li><strong>Testing</strong>: MockedProvider enables systematic testing for quality assurance</li><li><strong>Performance</strong>: Proper optimization techniques ensure scalable applications</li></ol><h4>Next Steps</h4><ul><li>Learn GraphQL schema design best practices</li><li>Explore full-stack development with Apollo Server</li><li>Implement real-time features using Subscriptions</li><li>Consider Apollo Federation for microservices architecture</li><li>Explore advanced caching strategies and normalization</li></ul><h4>Final Thoughts</h4><p>The combination of React, GraphQL, and Apollo Client creates a powerful development stack that enables building efficient, scalable, and maintainable web applications. The declarative nature of GraphQL, combined with Apollo Client’s intelligent caching and React’s component model, provides an excellent developer experience.</p><p>As the ecosystem continues to evolve, staying updated with the latest best practices and features will help you build even better applications. The investment in learning this stack will pay dividends in development speed, application performance, and user satisfaction.</p><p>Whether you’re building a simple blog or a complex enterprise application, the patterns and techniques covered in this guide provide a solid foundation for success. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01429593500c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing React SSE (Server-Sent Events): Real-time Notification System]]></title>
            <link>https://medium.com/@dlrnjstjs/implementing-react-sse-server-sent-events-real-time-notification-system-a999bb983d1b?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a999bb983d1b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 11:07:22 GMT</pubDate>
            <atom:updated>2025-09-21T11:07:22.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Real-time data transmission has become an essential feature in modern web applications. Users expect to receive the latest information without refreshing the page. One of the methods to implement this is Server-Sent Events (SSE).</p><p>SSE is a web standard technology for sending real-time data from server to client. Unlike WebSocket, it’s unidirectional communication, but it’s simple to implement and can leverage HTTP/2 advantages, making it suitable for real-time notifications, live feeds, and real-time updates.</p><h3>SSE vs WebSocket Comparison</h3><p><strong>Communication Direction:</strong></p><ul><li>SSE: Unidirectional (Server → Client)</li><li>WebSocket: Bidirectional</li></ul><p><strong>Protocol:</strong></p><ul><li>SSE: HTTP/HTTPS</li><li>WebSocket: WS/WSS</li></ul><p><strong>Implementation Complexity:</strong></p><ul><li>SSE: Simple</li><li>WebSocket: Complex</li></ul><p><strong>Auto-reconnection:</strong></p><ul><li>SSE: Supported</li><li>WebSocket: Manual implementation required</li></ul><p><strong>Browser Support:</strong></p><ul><li>Both: All modern browsers</li></ul><h3>1. Server-Side SSE Endpoint Implementation</h3><p>Let’s first implement an SSE server using Node.js and Express.</p><pre>// server.js<br>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();<br><br>// CORS configuration - allows client access to server<br>// origin: specifies which domain can make requests (React dev server address)<br>// credentials: allows requests with cookies or auth headers<br>app.use(cors({<br>  origin: &#39;http://localhost:3000&#39;, // React app address<br>  credentials: true<br>}));<br><br>// Array to store connected clients<br>// Each client has a unique ID and response object<br>let clients = [];<br><br>// SSE endpoint configuration<br>app.get(&#39;/api/notifications&#39;, (req, res) =&gt; {<br>  // Set headers required for SSE<br>  res.writeHead(200, {<br>    // &#39;text/event-stream&#39;: Standard MIME type for SSE<br>    // Tells browser to handle this response as EventSource<br>    &#39;Content-Type&#39;: &#39;text/event-stream&#39;,<br>    <br>    // &#39;no-cache&#39;: Prevents proxies or browsers from caching response<br>    // Essential for SSE as it&#39;s real-time data<br>    &#39;Cache-Control&#39;: &#39;no-cache&#39;,<br>    <br>    // &#39;keep-alive&#39;: Maintains HTTP connection<br>    // Required for SSE to keep connection open for long periods<br>    &#39;Connection&#39;: &#39;keep-alive&#39;,<br>    <br>    // CORS headers - compliance with browser security policies<br>    &#39;Access-Control-Allow-Origin&#39;: &#39;http://localhost:3000&#39;,<br>    &#39;Access-Control-Allow-Credentials&#39;: &#39;true&#39;<br>  });<br><br>  // Generate client ID based on current timestamp<br>  // Date.now() ensures unique identification for each client<br>  const clientId = Date.now();<br>  <br>  // Add new client to array<br>  // Store response object to send data later<br>  const newClient = {<br>    id: clientId,<br>    response: res // Store Express response object<br>  };<br>  clients.push(newClient);<br><br>  // Send initial message to confirm connection<br>  // SSE data format: &quot;data: [JSON data]\n\n&quot;<br>  // Two \n characters mark end of message (SSE standard)<br>  res.write(`data: ${JSON.stringify({<br>    type: &#39;connection&#39;, // Message type for connection confirmation<br>    message: &#39;Connected to notification service.&#39;,<br>    timestamp: new Date().toISOString() // ISO format timestamp<br>  })}\n\n`);<br><br>  // Remove client from array when connection closes<br>  // &#39;close&#39; event: triggered when client disconnects or closes browser<br>  req.on(&#39;close&#39;, () =&gt; {<br>    console.log(`Client ${clientId} disconnected`);<br>    // Use filter to remove only this client from array<br>    clients = clients.filter(client =&gt; client.id !== clientId);<br>  });<br>});<br><br>// Function to send notifications to all clients<br>function sendNotificationToAll(notification) {<br>  // forEach to send data to each client&#39;s response object<br>  // write() method writes data to stream<br>  clients.forEach(client =&gt; {<br>    // JSON.stringify converts object to string<br>    // Add &quot;data: &quot; prefix and &quot;\n\n&quot; suffix for SSE format<br>    client.response.write(`data: ${JSON.stringify(notification)}\n\n`);<br>  });<br>}<br><br>// Test: Generate random notifications every 5 seconds<br>setInterval(() =&gt; {<br>  // Array of various notification messages<br>  const notifications = [<br>    &#39;New message received.&#39;,<br>    &#39;System update completed.&#39;,<br>    &#39;New comment posted.&#39;,<br>    &#39;Discount event started.&#39;<br>  ];<br>  <br>  // Create random notification object<br>  const randomNotification = {<br>    type: &#39;notification&#39;, // Type indicating actual notification<br>    // Math.floor(Math.random() * length): random index from 0 to array length-1<br>    message: notifications[Math.floor(Math.random() * notifications.length)],<br>    timestamp: new Date().toISOString(), // Current time<br>    // Generate unique ID: random number converted to base-36 string<br>    id: Math.random().toString(36).substr(2, 9)<br>  };<br>  <br>  // Send notification to all connected clients<br>  sendNotificationToAll(randomNotification);<br>}, 5000); // 5000ms = 5 seconds<br><br>// Start server<br>const PORT = process.env.PORT || 5000; // Read port from env variable, default to 5000<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><p><strong>Server Code Detailed Analysis:</strong></p><ol><li><strong>CORS Configuration Importance</strong>: The credentials: true option allows requests with cookies or Authorization headers. This is essential for SSE when authentication is required.</li><li><strong>Client Array Management</strong>: We manage each client in an array to enable broadcasting (simultaneous transmission to all clients). In production, you might use Redis or other session stores.</li><li><strong>SSE Headers Role</strong>: The text/event-stream MIME type is crucial. Without this header, browsers won&#39;t recognize the response as EventSource-compatible.</li><li><strong>Data Format</strong>: SSE uses the data: [content]\n\n format. Two newline characters (\n\n) serve as message delimiters.</li></ol><h3>2. React SSE Client Implementation</h3><p>Now let’s implement SSE connection in React components to receive real-time notifications.</p><pre>// hooks/useSSE.js<br>import { useState, useEffect, useCallback, useRef } from &#39;react&#39;;<br><br>// Custom hook to manage SSE connection<br>export const useSSE = (url) =&gt; {<br>  // Store received data (only most recent message)<br>  const [data, setData] = useState(null);<br>  <br>  // Store error state (connection failures, parsing errors, etc.)<br>  const [error, setError] = useState(null);<br>  <br>  // Connection status (true: connected, false: disconnected/failed)<br>  const [isConnected, setIsConnected] = useState(false);<br>  <br>  // EventSource object reference - maintains same object across re-renders<br>  const eventSourceRef = useRef(null);<br>  <br>  // Reconnection timer reference - for cleanup on component unmount<br>  const reconnectTimeoutRef = useRef(null);<br><br>  // SSE connection function<br>  // useCallback memoizes function - creates new one only when dependencies (url) change<br>  const connect = useCallback(() =&gt; {<br>    try {<br>      // Close existing connection if present<br>      // Prevents duplicate connections before establishing new one<br>      if (eventSourceRef.current) {<br>        eventSourceRef.current.close();<br>      }<br><br>      // Create new EventSource object<br>      // EventSource: built-in browser API for managing SSE connections<br>      const eventSource = new EventSource(url);<br>      eventSourceRef.current = eventSource;<br><br>      // Event handler for successful connection<br>      // onopen: executed when EventSource successfully connects to server<br>      eventSource.onopen = () =&gt; {<br>        console.log(&#39;SSE connection opened&#39;);<br>        setIsConnected(true); // Update connection status<br>        setError(null); // Clear previous error state<br>      };<br><br>      // Event handler for message reception<br>      // onmessage: executed whenever server sends &quot;data:&quot; format message<br>      eventSource.onmessage = (event) =&gt; {<br>        try {<br>          // event.data: actual data sent by server (string format)<br>          // JSON.parse: convert string to JavaScript object<br>          const parsedData = JSON.parse(event.data);<br>          setData(parsedData); // Store parsed data in state<br>        } catch (parseError) {<br>          // Handle JSON parsing failure<br>          console.error(&#39;Error parsing SSE data:&#39;, parseError);<br>          setError(&#39;Data parsing error&#39;);<br>        }<br>      };<br><br>      // Event handler for errors<br>      // onerror: executed when connection fails, network errors occur, etc.<br>      eventSource.onerror = (event) =&gt; {<br>        console.error(&#39;SSE connection error:&#39;, event);<br>        setIsConnected(false); // Change connection status to false<br>        <br>        // Attempt auto-reconnection if connection is completely closed<br>        // EventSource.CLOSED: permanently closed connection state (value: 2)<br>        if (eventSource.readyState === EventSource.CLOSED) {<br>          setError(&#39;Connection lost. Attempting to reconnect...&#39;);<br>          <br>          // Retry connection after 3 seconds (prevents server overload from frequent attempts)<br>          reconnectTimeoutRef.current = setTimeout(() =&gt; {<br>            connect(); // Recursive call to retry connection<br>          }, 3000);<br>        }<br>      };<br><br>    } catch (err) {<br>      // Handle EventSource object creation failure<br>      console.error(&#39;Error creating SSE connection:&#39;, err);<br>      setError(&#39;Connection creation error&#39;);<br>    }<br>  }, [url]); // Create new connect function when url changes<br><br>  // Disconnect function<br>  const disconnect = useCallback(() =&gt; {<br>    // Close EventSource connection<br>    if (eventSourceRef.current) {<br>      eventSourceRef.current.close(); // Close connection<br>      eventSourceRef.current = null; // Reset reference<br>    }<br>    <br>    // Cancel reconnection timer if running<br>    if (reconnectTimeoutRef.current) {<br>      clearTimeout(reconnectTimeoutRef.current);<br>    }<br>    <br>    setIsConnected(false); // Update connection status<br>  }, []);<br><br>  // Connect on mount, disconnect on unmount<br>  useEffect(() =&gt; {<br>    connect(); // Auto-connect when component mounts<br>    <br>    // cleanup function: executed on component unmount<br>    // Prevents memory leaks by cleaning up connections<br>    return () =&gt; {<br>      disconnect();<br>    };<br>  }, [connect, disconnect]); // Re-execute if dependencies change<br><br>  // Return values and functions for external use<br>  return {<br>    data,        // Latest received data<br>    error,       // Error message<br>    isConnected, // Connection status<br>    connect,     // Manual connection function<br>    disconnect   // Manual disconnect function<br>  };<br>};</pre><p><strong>Custom Hook Detailed Analysis:</strong></p><ol><li><strong>useRef Usage Reason</strong>: eventSourceRef and reconnectTimeoutRef must maintain the same reference across component re-renders. Using useState would cause re-renders on state changes, making it inappropriate.</li><li><strong>useCallback Necessity</strong>: Memoizing connect and disconnect functions prevents unnecessary re-creation. This is especially important since they&#39;re included in useEffect dependency arrays.</li><li><strong>Error Handling Strategy</strong>: By checking readyState, we only attempt reconnection when the connection is completely closed. For temporary network issues, the browser automatically attempts reconnection, avoiding duplicates.</li><li><strong>Reconnection Delay</strong>: The 3-second delay prevents server overload and gives the network time to stabilize.</li></ol><h3>3. Real-time Notification Component Implementation</h3><pre>// components/NotificationSystem.jsx<br>import React, { useState, useEffect } from &#39;react&#39;;<br>import { useSSE } from &#39;../hooks/useSSE&#39;;<br>import &#39;./NotificationSystem.css&#39;;<br><br>const NotificationSystem = () =&gt; {<br>  // Notification list - array format to store multiple notifications<br>  // Each notification has id, message, timestamp, isRead, receivedAt properties<br>  const [notifications, setNotifications] = useState([]);<br>  <br>  // Unread notification count - managed separately for performance optimization<br>  const [unreadCount, setUnreadCount] = useState(0);<br>  <br>  // Use custom SSE hook - manages real-time connection with server<br>  const { data, error, isConnected } = useSSE(&#39;http://localhost:5000/api/notifications&#39;);<br><br>  // Effect executed whenever new data is received<br>  useEffect(() =&gt; {<br>    // Process only when data is not null (initial render has null data)<br>    if (data) {<br>      // Process only actual notifications, not connection confirmation messages<br>      // Distinguish by checking type sent from server<br>      if (data.type === &#39;notification&#39;) {<br>        // Create new notification object - add client-specific properties to server data<br>        const newNotification = {<br>          ...data, // Include all data from server (id, message, timestamp, etc.)<br>          isRead: false, // New notifications default to unread state<br>          receivedAt: new Date() // Record client reception time<br>        };<br>        <br>        // Add new notification to existing list (sorted by newest first)<br>        // Use functional update - calculate new state based on previous state<br>        setNotifications(prev =&gt; [newNotification, ...prev]); // Add to front of array<br>        <br>        // Increment unread notification count<br>        setUnreadCount(prev =&gt; prev + 1);<br>        <br>        // Show browser notification (if permission granted)<br>        // Notification.permission: one of &#39;granted&#39;, &#39;denied&#39;, &#39;default&#39;<br>        if (Notification.permission === &#39;granted&#39;) {<br>          // Create new browser notification<br>          new Notification(&#39;New Notification&#39;, {<br>            body: data.message, // Notification body text<br>            icon: &#39;/notification-icon.png&#39;, // Notification icon (must be in public folder)<br>            // Additional options available: tag, requireInteraction, etc.<br>          });<br>        }<br>      }<br>    }<br>  }, [data]); // Execute whenever data changes<br><br>  // Browser notification permission request function<br>  const requestNotificationPermission = async () =&gt; {<br>    // Check if browser supports Notification API<br>    if (&#39;Notification&#39; in window) {<br>      // Asynchronously request permission - wait for user to allow/deny<br>      const permission = await Notification.requestPermission();<br>      console.log(&#39;Notification permission:&#39;, permission);<br>      // Additional processing based on permission value possible<br>      // &#39;granted&#39;: allowed, &#39;denied&#39;: denied, &#39;default&#39;: not yet chosen<br>    }<br>  };<br><br>  // Request notification permission on component mount<br>  useEffect(() =&gt; {<br>    requestNotificationPermission();<br>  }, []); // Empty dependency array - execute once on component mount<br><br>  // Function to mark specific notification as read<br>  const markAsRead = (notificationId) =&gt; {<br>    // Use functional update to modify existing state<br>    setNotifications(prev =&gt; <br>      // Use map to modify only the notification with matching ID, keep others unchanged<br>      prev.map(notification =&gt; <br>        notification.id === notificationId <br>          ? { ...notification, isRead: true } // Change isRead to true for this notification<br>          : notification // Return other notifications unchanged<br>      )<br>    );<br>    <br>    // Decrease unread notification count (use Math.max to prevent going below 0)<br>    setUnreadCount(prev =&gt; Math.max(0, prev - 1));<br>  };<br><br>  // Function to mark all notifications as read<br>  const markAllAsRead = () =&gt; {<br>    setNotifications(prev =&gt; <br>      // Change isRead to true for all notifications<br>      prev.map(notification =&gt; ({ ...notification, isRead: true }))<br>    );<br>    // Reset unread notification count to 0<br>    setUnreadCount(0);<br>  };<br><br>  // Function to delete specific notification<br>  const deleteNotification = (notificationId) =&gt; {<br>    setNotifications(prev =&gt; {<br>      // Find notification to delete (to check if it was unread)<br>      const notification = prev.find(n =&gt; n.id === notificationId);<br>      <br>      // Create new array excluding notification with this ID<br>      const newNotifications = prev.filter(n =&gt; n.id !== notificationId);<br>      <br>      // Decrease count if it was unread notification<br>      if (notification &amp;&amp; !notification.isRead) {<br>        setUnreadCount(count =&gt; Math.max(0, count - 1));<br>      }<br>      <br>      return newNotifications;<br>    });<br>  };<br><br>  // Function to delete all notifications<br>  const clearAllNotifications = () =&gt; {<br>    setNotifications([]); // Reset to empty array<br>    setUnreadCount(0); // Reset unread count to 0<br>  };<br><br>  return (<br>    &lt;div className=&quot;notification-system&quot;&gt;<br>      {/* Connection status display */}<br>      &lt;div className=&quot;connection-status&quot;&gt;<br>        &lt;div className={`status-indicator ${isConnected ? &#39;connected&#39; : &#39;disconnected&#39;}`}&gt;<br>          {/* Conditional rendering to show different text and emoji based on connection status */}<br>          {isConnected ? &#39;🟢 Connected&#39; : &#39;🔴 Disconnected&#39;}<br>        &lt;/div&gt;<br>        {/* Show error message only when error exists */}<br>        {error &amp;&amp; &lt;div className=&quot;error-message&quot;&gt;⚠️ {error}&lt;/div&gt;}<br>      &lt;/div&gt;<br><br>      {/* Notification header */}<br>      &lt;div className=&quot;notification-header&quot;&gt;<br>        &lt;h3&gt;Real-time Notifications&lt;/h3&gt;<br>        &lt;div className=&quot;notification-controls&quot;&gt;<br>          {/* Show badge only when there are unread notifications */}<br>          {unreadCount &gt; 0 &amp;&amp; (<br>            &lt;span className=&quot;unread-badge&quot;&gt;{unreadCount}&lt;/span&gt;<br>          )}<br>          {/* Show buttons only when there&#39;s at least one notification */}<br>          {notifications.length &gt; 0 &amp;&amp; (<br>            &lt;&gt;<br>              &lt;button onClick={markAllAsRead} className=&quot;btn-secondary&quot;&gt;<br>                Mark All Read<br>              &lt;/button&gt;<br>              &lt;button onClick={clearAllNotifications} className=&quot;btn-danger&quot;&gt;<br>                Clear All<br>              &lt;/button&gt;<br>            &lt;/&gt;<br>          )}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      {/* Notification list */}<br>      &lt;div className=&quot;notifications-list&quot;&gt;<br>        {notifications.length === 0 ? (<br>          // Message to display when no notifications exist<br>          &lt;div className=&quot;no-notifications&quot;&gt;<br>            📭 No notifications.<br>          &lt;/div&gt;<br>        ) : (<br>          // Render notification list using map<br>          notifications.map((notification) =&gt; (<br>            &lt;div <br>              key={notification.id} // Unique key for React list rendering<br>              className={`notification-item ${notification.isRead ? &#39;read&#39; : &#39;unread&#39;}`}<br>            &gt;<br>              &lt;div className=&quot;notification-content&quot;&gt;<br>                &lt;div className=&quot;notification-message&quot;&gt;<br>                  {notification.message}<br>                &lt;/div&gt;<br>                &lt;div className=&quot;notification-time&quot;&gt;<br>                  {/* Convert timestamp to US time format */}<br>                  {new Date(notification.timestamp).toLocaleString(&#39;en-US&#39;)}<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;notification-actions&quot;&gt;<br>                {/* Show &#39;Read&#39; button only for unread notifications */}<br>                {!notification.isRead &amp;&amp; (<br>                  &lt;button <br>                    onClick={() =&gt; markAsRead(notification.id)} // Mark this ID&#39;s notification as read<br>                    className=&quot;btn-read&quot;<br>                  &gt;<br>                    Read<br>                  &lt;/button&gt;<br>                )}<br>                {/* Show delete button for all notifications */}<br>                &lt;button <br>                  onClick={() =&gt; deleteNotification(notification.id)}<br>                  className=&quot;btn-delete&quot;<br>                &gt;<br>                  Delete<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          ))<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default NotificationSystem;</pre><p><strong>Component Detailed Analysis:</strong></p><ol><li><strong>State Management Strategy</strong>: Separating notifications array and unreadCount number provides performance optimization. Instead of iterating through the array each time to calculate unread notifications, we maintain a separate counter.</li><li><strong>Functional Updates</strong>: Using functional updates like setNotifications(prev =&gt; ...) ensures the latest state is guaranteed. This is safe for asynchronous operations or rapid state changes.</li><li><strong>Conditional Rendering</strong>: Using the &amp;&amp; operator for conditional rendering displays UI elements only when necessary. This prevents unnecessary DOM node creation.</li><li><strong>Browser Notification Integration</strong>: Utilizing the Web Notification API allows users to receive notifications even when the page is in the background.</li></ol><h3>4. CSS Styling</h3><pre>/* components/NotificationSystem.css */<br><br>/* Main container - box wrapping entire notification system */<br>.notification-system {<br>  max-width: 600px; /* Limit max width for better readability */<br>  margin: 20px auto; /* Center alignment */<br>  padding: 20px; /* Internal spacing */<br>  border-radius: 8px; /* Rounded corners */<br>  background-color: #f8f9fa; /* Light gray background */<br>  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* Shadow for depth */<br>}<br><br>/* Connection status display area */<br>.connection-status {<br>  margin-bottom: 20px; /* Bottom margin */<br>  padding: 10px; /* Internal spacing */<br>  border-radius: 4px; /* Slightly rounded corners */<br>  background-color: white; /* White background for distinction */<br>}<br><br>/* Connection status text styling */<br>.status-indicator {<br>  font-weight: bold; /* Bold text */<br>  margin-bottom: 5px; /* Bottom margin */<br>}<br><br>/* Connected state - green text */<br>.status-indicator.connected {<br>  color: #28a745; /* Bootstrap success color */<br>}<br><br>/* Disconnected state - red text */<br>.status-indicator.disconnected {<br>  color: #dc3545; /* Bootstrap danger color */<br>}<br><br>/* Error message styling */<br>.error-message {<br>  color: #dc3545; /* Red text */<br>  font-size: 14px; /* Smaller font size */<br>}<br><br>/* Notification header - area containing title and controls */<br>.notification-header {<br>  display: flex; /* Flexbox layout */<br>  justify-content: space-between; /* Align to both ends */<br>  align-items: center; /* Vertical center alignment */<br>  margin-bottom: 20px; /* Bottom margin */<br>  padding-bottom: 10px; /* Bottom internal spacing */<br>  border-bottom: 2px solid #dee2e6; /* Bottom divider line */<br>}<br><br>/* Container wrapping notification control buttons */<br>.notification-controls {<br>  display: flex; /* Flexbox layout */<br>  align-items: center; /* Vertical center alignment */<br>  gap: 10px; /* Spacing between elements */<br>}<br><br>/* Unread notification count badge */<br>.unread-badge {<br>  background-color: #dc3545; /* Red background */<br>  color: white; /* White text */<br>  border-radius: 50%; /* Circular shape */<br>  padding: 4px 8px; /* Internal spacing */<br>  font-size: 12px; /* Small font */<br>  font-weight: bold; /* Bold text */<br>}<br><br>/* Basic button styles */<br>.btn-secondary {<br>  background-color: #6c757d; /* Gray background */<br>  color: white; /* White text */<br>  border: none; /* Remove border */<br>  padding: 6px 12px; /* Internal spacing */<br>  border-radius: 4px; /* Rounded corners */<br>  cursor: pointer; /* Change mouse pointer */<br>  font-size: 12px; /* Small font */<br>  transition: background-color 0.2s ease; /* Transition for hover effect */<br>}<br><br>/* Hover effect */<br>.btn-secondary:hover {<br>  background-color: #5a6268; /* Darker gray */<br>}<br><br>.btn-danger {<br>  background-color: #dc3545; /* Red background */<br>  color: white; /* White text */<br>  border: none;<br>  padding: 6px 12px;<br>  border-radius: 4px;<br>  cursor: pointer;<br>  font-size: 12px;<br>  transition: background-color 0.2s ease;<br>}<br><br>.btn-danger:hover {<br>  background-color: #c82333; /* Darker red */<br>}<br><br>.btn-read {<br>  background-color: #007bff; /* Blue background */<br>  color: white;<br>  border: none;<br>  padding: 4px 8px; /* Smaller padding */<br>  border-radius: 4px;<br>  cursor: pointer;<br>  font-size: 11px; /* Smaller font */<br>  transition: background-color 0.2s ease;<br>}<br><br>.btn-read:hover {<br>  background-color: #0056b3; /* Darker blue */<br>}<br><br>.btn-delete {<br>  background-color: #dc3545;<br>  color: white;<br>  border: none;<br>  padding: 4px 8px;<br>  border-radius: 4px;<br>  cursor: pointer;<br>  font-size: 11px;<br>  transition: background-color 0.2s ease;<br>}<br><br>.btn-delete:hover {<br>  background-color: #c82333;<br>}<br><br>/* Notification list container */<br>.notifications-list {<br>  max-height: 400px; /* Maximum height limit */<br>  overflow-y: auto; /* Enable vertical scrolling */<br>  /* Scrollbar styling (for webkit browsers) */<br>  scrollbar-width: thin; /* For Firefox */<br>}<br><br>/* Webkit-based browser scrollbar styles */<br>.notifications-list::-webkit-scrollbar {<br>  width: 6px; /* Scrollbar width */<br>}<br><br>.notifications-list::-webkit-scrollbar-track {<br>  background: #f1f1f1; /* Scrollbar track color */<br>  border-radius: 3px;<br>}<br><br>.notifications-list::-webkit-scrollbar-thumb {<br>  background: #c1c1c1; /* Scrollbar handle color */<br>  border-radius: 3px;<br>}<br><br>.notifications-list::-webkit-scrollbar-thumb:hover {<br>  background: #a8a8a8; /* Hover color */<br>}<br><br>/* Message to display when no notifications exist */<br>.no-notifications {<br>  text-align: center; /* Center alignment */<br>  padding: 40px 20px; /* Sufficient spacing */<br>  color: #6c757d; /* Gray text */<br>  font-size: 16px; /* Appropriate font size */<br>}<br><br>/* Individual notification item */<br>.notification-item {<br>  display: flex; /* Flexbox layout */<br>  justify-content: space-between; /* Content and buttons to both ends */<br>  align-items: flex-start; /* Top alignment (considering multi-line text) */<br>  padding: 15px; /* Internal spacing */<br>  margin-bottom: 10px; /* Spacing between items */<br>  border-radius: 6px; /* Rounded corners */<br>  background-color: white; /* White background */<br>  border-left: 4px solid transparent; /* Left color bar (default transparent) */<br>  transition: all 0.3s ease; /* Smooth transition effect */<br>  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* Subtle shadow */<br>}<br><br>/* Unread notification styling */<br>.notification-item.unread {<br>  border-left-color: #007bff; /* Blue left bar */<br>  background-color: #e3f2fd; /* Light blue background */<br>  animation: fadeIn 0.3s ease; /* Fade-in effect when appearing */<br>}<br><br>/* Read notification styling */<br>.notification-item.read {<br>  border-left-color: #28a745; /* Green left bar */<br>  opacity: 0.8; /* Slightly transparent */<br>}<br><br>/* Fade-in animation */<br>@keyframes fadeIn {<br>  from {<br>    opacity: 0;<br>    transform: translateY(-10px); /* Appear from top to bottom */<br>  }<br>  to {<br>    opacity: 1;<br>    transform: translateY(0);<br>  }<br>}<br><br>/* Notification content area */<br>.notification-content {<br>  flex: 1; /* Use all remaining space */<br>  margin-right: 10px; /* Spacing from buttons */<br>}<br><br>/* Notification message text */<br>.notification-message {<br>  font-weight: 500; /* Slightly bold text */<br>  margin-bottom: 5px; /* Bottom margin */<br>  color: #333; /* Dark gray */<br>  line-height: 1.4; /* Line spacing */<br>}<br><br>/* Notification time text */<br>.notification-time {<br>  font-size: 12px; /* Small font */<br>  color: #6c757d; /* Light gray */<br>  font-style: italic; /* Italic */<br>}<br><br>/* Container wrapping notification action buttons */<br>.notification-actions {<br>  display: flex; /* Flexbox layout */<br>  flex-direction: column; /* Vertical alignment */<br>  gap: 5px; /* Spacing between buttons */<br>  margin-left: 10px; /* Left margin */<br>}<br><br>/* Responsive design - for small screens */<br>@media (max-width: 768px) {<br>  .notification-system {<br>    margin: 10px; /* Reduce margins */<br>    padding: 15px; /* Reduce padding */<br>  }<br>  <br>  .notification-header {<br>    flex-direction: column; /* Change to vertical direction */<br>    align-items: flex-start; /* Left alignment */<br>    gap: 10px; /* Spacing between elements */<br>  }<br>  <br>  .notification-item {<br>    flex-direction: column; /* Change to vertical direction */<br>    align-items: stretch; /* Use full width */<br>  }<br>  <br>  .notification-actions {<br>    flex-direction: row; /* Buttons in horizontal direction */<br>    margin-top: 10px; /* Top margin */<br>    margin-left: 0; /* Remove left margin */<br>  }<br>}</pre><p><strong>CSS Detailed Analysis:</strong></p><ol><li><strong>Modern Design Patterns</strong>: Implements contemporary UI with card-based layout, subtle shadows, and color coding.</li><li><strong>Accessibility Considerations</strong>: Provides smooth interactions with transition properties and maintains sufficient color contrast.</li><li><strong>Responsive Design</strong>: Uses @media queries to adjust layout for mobile environments.</li><li><strong>State-based Visual Feedback</strong>: Intuitively represents read/unread status and connection states with colors and transparency.</li></ol><h3>5. Main App Component Usage</h3><pre>// App.js<br>import React from &#39;react&#39;;<br>import NotificationSystem from &#39;./components/NotificationSystem&#39;;<br>import &#39;./App.css&#39;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;h1&gt;React SSE Real-time Notification System&lt;/h1&gt;<br>        &lt;p&gt;Real-time notification demo using Server-Sent Events&lt;/p&gt;<br>      &lt;/header&gt;<br>      <br>      &lt;main&gt;<br>        {/* <br>          NotificationSystem component manages SSE connection internally,<br>          so no additional props or state management required<br>        */}<br>        &lt;NotificationSystem /&gt;<br>        <br>        {/* <br>          In real applications, consider using Context API or state management<br>          libraries to share the same SSE connection across multiple components<br>        */}<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>6. Advanced Features Implementation</h3><h4>Notification Type Handling</h4><pre>// components/AdvancedNotificationSystem.jsx<br>const NotificationSystem = () =&gt; {<br>  // Define icons and styles for different notification types<br>  // Provide unique visual representation for each type<br>  const getNotificationStyle = (type) =&gt; {<br>    const styles = {<br>      // Information notification: blue theme<br>      info: { icon: &#39;📢&#39;, color: &#39;#17a2b8&#39;, bgColor: &#39;#d1ecf1&#39; },<br>      // Success notification: green theme  <br>      success: { icon: &#39;✅&#39;, color: &#39;#28a745&#39;, bgColor: &#39;#d4edda&#39; },<br>      // Warning notification: yellow theme<br>      warning: { icon: &#39;⚠️&#39;, color: &#39;#ffc107&#39;, bgColor: &#39;#fff3cd&#39; },<br>      // Error notification: red theme<br>      error: { icon: &#39;❌&#39;, color: &#39;#dc3545&#39;, bgColor: &#39;#f8d7da&#39; },<br>      // Message notification: default blue<br>      message: { icon: &#39;💬&#39;, color: &#39;#007bff&#39;, bgColor: &#39;#e3f2fd&#39; }<br>    };<br>    <br>    // Use info style as fallback for undefined types<br>    return styles[type] || styles.info;<br>  };<br><br>  // Define notification priority (higher number = higher priority)<br>  const getPriority = (type) =&gt; {<br>    const priorities = {<br>      error: 4,   // Error has highest priority<br>      warning: 3, // Warning is second<br>      info: 2,    // Info is third<br>      success: 1, // Success is fourth<br>      message: 0  // General message has lowest priority<br>    };<br>    return priorities[type] || 0;<br>  };<br><br>  // Notification sorting function - based on priority and time<br>  const sortNotifications = (notifications) =&gt; {<br>    return notifications.sort((a, b) =&gt; {<br>      // First sort by priority (higher priority goes to top)<br>      const priorityDiff = getPriority(b.type) - getPriority(a.type);<br>      if (priorityDiff !== 0) return priorityDiff;<br>      <br>      // If priority is same, sort by time (newest goes to top)<br>      return new Date(b.timestamp) - new Date(a.timestamp);<br>    });<br>  };<br><br>  // Render notification with type-specific styling<br>  const renderNotification = (notification) =&gt; {<br>    const style = getNotificationStyle(notification.type);<br>    <br>    return (<br>      &lt;div <br>        key={notification.id}<br>        className={`notification-item ${notification.isRead ? &#39;read&#39; : &#39;unread&#39;}`}<br>        style={{ <br>          borderLeftColor: style.color,<br>          backgroundColor: notification.isRead ? &#39;#f8f9fa&#39; : style.bgColor <br>        }}<br>      &gt;<br>        {/* Display type-specific icon */}<br>        &lt;div className=&quot;notification-icon&quot; style={{ color: style.color }}&gt;<br>          {style.icon}<br>        &lt;/div&gt;<br>        <br>        &lt;div className=&quot;notification-content&quot;&gt;<br>          {/* Notification type label (optional) */}<br>          &lt;div className=&quot;notification-type&quot; style={{ color: style.color }}&gt;<br>            {notification.type.toUpperCase()}<br>          &lt;/div&gt;<br>          <br>          &lt;div className=&quot;notification-message&quot;&gt;<br>            {notification.message}<br>          &lt;/div&gt;<br>          <br>          &lt;div className=&quot;notification-time&quot;&gt;<br>            {new Date(notification.timestamp).toLocaleString(&#39;en-US&#39;)}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        <br>        &lt;div className=&quot;notification-actions&quot;&gt;<br>          {!notification.isRead &amp;&amp; (<br>            &lt;button <br>              onClick={() =&gt; markAsRead(notification.id)}<br>              className=&quot;btn-read&quot;<br>            &gt;<br>              Read<br>            &lt;/button&gt;<br>          )}<br>          &lt;button <br>            onClick={() =&gt; deleteNotification(notification.id)}<br>            className=&quot;btn-delete&quot;<br>          &gt;<br>            Delete<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  };<br><br>  // Use sorted notification list<br>  const sortedNotifications = sortNotifications(notifications);<br><br>  // ... rest of component code<br>};</pre><h4>Notification Filtering and Search</h4><pre>// Add filtering states<br>const [filter, setFilter] = useState(&#39;all&#39;); // all, unread, read, type-specific filter<br>const [searchTerm, setSearchTerm] = useState(&#39;&#39;); // search term<br>const [selectedTypes, setSelectedTypes] = useState([]); // selected types<br><br>// Advanced filtering logic<br>const getFilteredNotifications = () =&gt; {<br>  return notifications.filter(notification =&gt; {<br>    // 1. Check read status filter<br>    const statusMatch = filter === &#39;all&#39; || <br>      (filter === &#39;unread&#39; &amp;&amp; !notification.isRead) ||<br>      (filter === &#39;read&#39; &amp;&amp; notification.isRead);<br>    <br>    // 2. Check search term filter (case-insensitive, partial match)<br>    const searchMatch = searchTerm === &#39;&#39; || <br>      notification.message.toLowerCase().includes(searchTerm.toLowerCase()) ||<br>      notification.type.toLowerCase().includes(searchTerm.toLowerCase());<br>    <br>    // 3. Check type filter (only when types are selected)<br>    const typeMatch = selectedTypes.length === 0 || <br>      selectedTypes.includes(notification.type);<br>    <br>    // Only notifications meeting all conditions pass through<br>    return statusMatch &amp;&amp; searchMatch &amp;&amp; typeMatch;<br>  });<br>};<br><br>// Filtering UI construction<br>const renderFilters = () =&gt; (<br>  &lt;div className=&quot;notification-filters&quot;&gt;<br>    {/* Status filter buttons */}<br>    &lt;div className=&quot;status-filters&quot;&gt;<br>      {[&#39;all&#39;, &#39;unread&#39;, &#39;read&#39;].map(status =&gt; (<br>        &lt;button<br>          key={status}<br>          onClick={() =&gt; setFilter(status)}<br>          className={`filter-btn ${filter === status ? &#39;active&#39; : &#39;&#39;}`}<br>        &gt;<br>          {status === &#39;all&#39; ? &#39;All&#39; : status === &#39;unread&#39; ? &#39;Unread&#39; : &#39;Read&#39;}<br>        &lt;/button&gt;<br>      ))}<br>    &lt;/div&gt;<br>    <br>    {/* Search input field */}<br>    &lt;div className=&quot;search-filter&quot;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Search notifications...&quot;<br>        value={searchTerm}<br>        onChange={(e) =&gt; setSearchTerm(e.target.value)}<br>        className=&quot;search-input&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>    <br>    {/* Type-specific filter checkboxes */}<br>    &lt;div className=&quot;type-filters&quot;&gt;<br>      {[&#39;info&#39;, &#39;success&#39;, &#39;warning&#39;, &#39;error&#39;, &#39;message&#39;].map(type =&gt; (<br>        &lt;label key={type} className=&quot;type-filter-label&quot;&gt;<br>          &lt;input<br>            type=&quot;checkbox&quot;<br>            checked={selectedTypes.includes(type)}<br>            onChange={(e) =&gt; {<br>              if (e.target.checked) {<br>                setSelectedTypes([...selectedTypes, type]);<br>              } else {<br>                setSelectedTypes(selectedTypes.filter(t =&gt; t !== type));<br>              }<br>            }}<br>          /&gt;<br>          {type}<br>        &lt;/label&gt;<br>      ))}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>);</pre><p><strong>Advanced Features Detailed Analysis:</strong></p><ol><li><strong>Type-based Priority</strong>: Important notifications like errors or warnings are displayed at the top to capture user attention.</li><li><strong>Multi-filter Combination</strong>: Status, search term, and type filters can be applied simultaneously for precise filtering.</li><li><strong>Visual Differentiation</strong>: Different colors and icons for each type provide an intuitive interface.</li><li><strong>Search Functionality</strong>: Case-insensitive substring matching on both message content and notification type provides flexible search capabilities.</li></ol><h3>7. SSE Usage Considerations</h3><h4>Advantages</h4><p><strong>Implementation Simplicity:</strong> SSE is much simpler to implement than WebSocket. It leverages standard HTTP protocols without requiring complex handshake procedures or custom protocols.</p><p><strong>Automatic Reconnection:</strong> Browsers handle reconnection automatically when connections drop, reducing the need for custom reconnection logic.</p><p><strong>HTTP Compatibility:</strong> SSE works seamlessly with existing HTTP infrastructure, including proxies, load balancers, and CDNs, without special configuration.</p><p><strong>Low Overhead:</strong> In HTTP/2 environments, SSE can efficiently maintain multiple connections with minimal overhead due to multiplexing capabilities.</p><h4>Disadvantages</h4><p><strong>Unidirectional Communication:</strong> SSE only supports server-to-client communication. If you need bidirectional real-time communication, WebSocket is more appropriate.</p><p><strong>Browser Connection Limits:</strong> Browsers typically limit concurrent connections per domain (usually 6), which can be restrictive for applications requiring many simultaneous SSE connections.</p><p><strong>Text-Only Data:</strong> SSE is designed for text data. While you can encode binary data as Base64, this adds overhead and complexity.</p><h4>Performance Optimization Tips</h4><p><strong>Connection Pooling:</strong> Design your application so multiple features share a single SSE connection rather than creating separate connections for each feature. This conserves browser connection limits and reduces server resource usage.</p><pre>// Connection sharing using Context<br>const SSEContext = createContext();<br><br>const SSEProvider = ({ children }) =&gt; {<br>  const sseData = useSSE(&#39;/api/events&#39;);<br>  return (<br>    &lt;SSEContext.Provider value={sseData}&gt;<br>      {children}<br>    &lt;/SSEContext.Provider&gt;<br>  );<br>};<br><br>// Usage in components<br>const useSSEContext = () =&gt; {<br>  const context = useContext(SSEContext);<br>  if (!context) {<br>    throw new Error(&#39;useSSEContext must be used within SSEProvider&#39;);<br>  }<br>  return context;<br>};</pre><p><strong>Message Compression:</strong> For large data payloads, implement compression on the server side. You can use libraries like zlib to compress JSON data before sending.</p><pre>// Server-side gzip compression<br>const zlib = require(&#39;zlib&#39;);<br><br>const compressedData = zlib.gzipSync(JSON.stringify(largeData));<br>res.write(`data: ${compressedData.toString(&#39;base64&#39;)}\n\n`);<br><br>// Client-side decompression<br>const decompressData = (compressedBase64) =&gt; {<br>  const buffer = Buffer.from(compressedBase64, &#39;base64&#39;);<br>  const decompressed = zlib.gunzipSync(buffer);<br>  return JSON.parse(decompressed.toString());<br>};</pre><p><strong>Client-Side Buffering:</strong> Implement message buffering on the client side to batch UI updates. Instead of updating the UI for every incoming message, collect messages and update in batches to improve performance.</p><pre>// Buffering for batch updates<br>const [messageBuffer, setMessageBuffer] = useState([]);<br><br>useEffect(() =&gt; {<br>  const timer = setInterval(() =&gt; {<br>    if (messageBuffer.length &gt; 0) {<br>      setNotifications(prev =&gt; [...messageBuffer, ...prev]);<br>      setMessageBuffer([]);<br>    }<br>  }, 100); // Batch process every 100ms<br><br>  return () =&gt; clearInterval(timer);<br>}, [messageBuffer]);<br><br>// Add to buffer instead of direct state update<br>const addToBuffer = (newNotification) =&gt; {<br>  setMessageBuffer(prev =&gt; [...prev, newNotification]);<br>};</pre><p><strong>Error Handling:</strong> Implement robust error handling for network instability situations. Include exponential backoff for reconnection attempts and graceful degradation when connections fail.</p><pre>// Exponential backoff reconnection<br>const reconnectWithBackoff = (attempt = 1) =&gt; {<br>  const delay = Math.min(1000 * Math.pow(2, attempt), 30000); // Max 30 seconds<br>  <br>  setTimeout(() =&gt; {<br>    if (attempt &lt;= 5) { // Maximum 5 attempts<br>      connect();<br>    } else {<br>      setError(&#39;Unable to restore connection. Please refresh the page.&#39;);<br>    }<br>  }, delay);<br>};<br><br>// Enhanced error handling in SSE hook<br>eventSource.onerror = (event) =&gt; {<br>  console.error(&#39;SSE connection error:&#39;, event);<br>  setIsConnected(false);<br>  <br>  if (eventSource.readyState === EventSource.CLOSED) {<br>    setError(`Connection lost. Reconnecting... (Attempt ${reconnectAttempt})`);<br>    reconnectWithBackoff(reconnectAttempt);<br>    setReconnectAttempt(prev =&gt; prev + 1);<br>  }<br>};</pre><p><strong>Message Deduplication:</strong> Implement message deduplication both on server and client sides to handle potential duplicate messages during reconnection scenarios.</p><pre>// Client-side deduplication<br>const [processedMessageIds, setProcessedMessageIds] = useState(new Set());<br><br>const processMessage = (newMessage) =&gt; {<br>  // Check if message was already processed<br>  if (processedMessageIds.has(newMessage.id)) {<br>    console.log(&#39;Duplicate message detected, skipping:&#39;, newMessage.id);<br>    return;<br>  }<br>  <br>  // Add to processed set<br>  setProcessedMessageIds(prev =&gt; new Set([...prev, newMessage.id]));<br>  <br>  // Process the message<br>  setNotifications(prev =&gt; [newMessage, ...prev]);<br>  <br>  // Clean up old IDs periodically (keep last 1000)<br>  if (processedMessageIds.size &gt; 1000) {<br>    const idsArray = Array.from(processedMessageIds);<br>    const recentIds = idsArray.slice(-500); // Keep last 500<br>    setProcessedMessageIds(new Set(recentIds));<br>  }<br>};</pre><p><strong>Resource Cleanup:</strong> Ensure proper cleanup of event listeners and connections to prevent memory leaks, especially in single-page applications where components mount and unmount frequently.</p><pre>// Comprehensive cleanup<br>useEffect(() =&gt; {<br>  const eventSource = new EventSource(url);<br>  <br>  // Store all event listeners for cleanup<br>  const listeners = {<br>    open: () =&gt; setIsConnected(true),<br>    message: handleMessage,<br>    error: handleError<br>  };<br>  <br>  // Add listeners<br>  Object.entries(listeners).forEach(([event, handler]) =&gt; {<br>    eventSource.addEventListener(event, handler);<br>  });<br>  <br>  // Cleanup function<br>  return () =&gt; {<br>    // Remove all listeners<br>    Object.entries(listeners).forEach(([event, handler]) =&gt; {<br>      eventSource.removeEventListener(event, handler);<br>    });<br>    <br>    // Close connection<br>    eventSource.close();<br>    <br>    // Clear any pending timeouts<br>    if (reconnectTimeoutRef.current) {<br>      clearTimeout(reconnectTimeoutRef.current);<br>    }<br>  };<br>}, [url]);</pre><h4>Production Deployment Considerations</h4><h4>Server Configuration</h4><p><strong>Load Balancing:</strong> When using multiple server instances, ensure session stickiness or implement a shared message broker like Redis for coordinating messages across instances.</p><pre>// Redis-based message broadcasting<br>const redis = require(&#39;redis&#39;);<br>const publisher = redis.createClient();<br>const subscriber = redis.createClient();<br><br>// Subscribe to notification channel<br>subscriber.subscribe(&#39;notifications&#39;);<br>subscriber.on(&#39;message&#39;, (channel, message) =&gt; {<br>  if (channel === &#39;notifications&#39;) {<br>    sendNotificationToAll(JSON.parse(message));<br>  }<br>});<br><br>// Publish notification to all instances<br>const broadcastNotification = (notification) =&gt; {<br>  publisher.publish(&#39;notifications&#39;, JSON.stringify(notification));<br>};</pre><p><strong>Security Considerations:</strong> Implement proper authentication and authorization for SSE endpoints.</p><pre>// JWT-based authentication for SSE<br>app.get(&#39;/api/notifications&#39;, authenticateJWT, (req, res) =&gt; {<br>  // Verify user permissions<br>  if (!req.user.canReceiveNotifications) {<br>    return res.status(403).json({ error: &#39;Insufficient permissions&#39; });<br>  }<br>  <br>  // Add user ID to client for targeted notifications<br>  const newClient = {<br>    id: Date.now(),<br>    userId: req.user.id,<br>    response: res<br>  };<br>  <br>  clients.push(newClient);<br>  // ... rest of SSE setup<br>});<br><br>// Send notifications to specific users<br>const sendNotificationToUser = (userId, notification) =&gt; {<br>  const userClients = clients.filter(client =&gt; client.userId === userId);<br>  userClients.forEach(client =&gt; {<br>    client.response.write(`data: ${JSON.stringify(notification)}\n\n`);<br>  });<br>};</pre><p><strong>Rate Limiting:</strong> Implement rate limiting to prevent abuse and ensure system stability.</p><pre>const rateLimit = require(&#39;express-rate-limit&#39;);<br><br>const sseRateLimit = rateLimit({<br>  windowMs: 15 * 60 * 1000, // 15 minutes<br>  max: 5, // Maximum 5 SSE connections per IP per window<br>  message: &#39;Too many SSE connections from this IP&#39;,<br>  standardHeaders: true,<br>  legacyHeaders: false,<br>});<br><br>app.get(&#39;/api/notifications&#39;, sseRateLimit, (req, res) =&gt; {<br>  // SSE endpoint logic<br>});</pre><h4>Monitoring and Analytics</h4><p><strong>Connection Metrics:</strong> Track connection statistics for monitoring system health.</p><pre>// Connection metrics tracking<br>let connectionMetrics = {<br>  totalConnections: 0,<br>  activeConnections: 0,<br>  reconnectAttempts: 0,<br>  avgConnectionDuration: 0<br>};<br><br>// Track connection events<br>const trackConnection = (clientId, event) =&gt; {<br>  switch (event) {<br>    case &#39;connect&#39;:<br>      connectionMetrics.totalConnections++;<br>      connectionMetrics.activeConnections++;<br>      break;<br>    case &#39;disconnect&#39;:<br>      connectionMetrics.activeConnections--;<br>      break;<br>    case &#39;reconnect&#39;:<br>      connectionMetrics.reconnectAttempts++;<br>      break;<br>  }<br>  <br>  // Send metrics to monitoring service<br>  sendMetricsToMonitoring(connectionMetrics);<br>};</pre><p><strong>Client-side Analytics:</strong> Track user engagement with notifications.</p><pre>// Analytics integration<br>const trackNotificationEvent = (event, notificationId) =&gt; {<br>  // Send to analytics service<br>  analytics.track(&#39;notification_event&#39;, {<br>    event_type: event, // &#39;received&#39;, &#39;read&#39;, &#39;dismissed&#39;, etc.<br>    notification_id: notificationId,<br>    timestamp: new Date().toISOString(),<br>    user_agent: navigator.userAgent<br>  });<br>};<br><br>// Track in notification handlers<br>const markAsRead = (notificationId) =&gt; {<br>  setNotifications(prev =&gt; <br>    prev.map(notification =&gt; <br>      notification.id === notificationId <br>        ? { ...notification, isRead: true }<br>        : notification<br>    )<br>  );<br>  <br>  // Track read event<br>  trackNotificationEvent(&#39;read&#39;, notificationId);<br>  setUnreadCount(prev =&gt; Math.max(0, prev - 1));<br>};</pre><h4>Testing Strategies</h4><h4>Unit Testing</h4><pre>// Testing the useSSE hook<br>import { renderHook, act } from &#39;@testing-library/react&#39;;<br>import { useSSE } from &#39;../hooks/useSSE&#39;;<br><br>// Mock EventSource<br>global.EventSource = jest.fn(() =&gt; ({<br>  close: jest.fn(),<br>  addEventListener: jest.fn(),<br>  removeEventListener: jest.fn()<br>}));<br><br>describe(&#39;useSSE&#39;, () =&gt; {<br>  test(&#39;establishes connection on mount&#39;, () =&gt; {<br>    const { result } = renderHook(() =&gt; useSSE(&#39;http://test-url&#39;));<br>    <br>    expect(global.EventSource).toHaveBeenCalledWith(&#39;http://test-url&#39;);<br>    expect(result.current.isConnected).toBe(false); // Initially false<br>  });<br>  <br>  test(&#39;handles message reception&#39;, () =&gt; {<br>    const { result } = renderHook(() =&gt; useSSE(&#39;http://test-url&#39;));<br>    <br>    // Simulate message<br>    const mockMessage = { data: JSON.stringify({ message: &#39;test&#39; }) };<br>    act(() =&gt; {<br>      // Trigger onmessage event<br>      result.current.data = { message: &#39;test&#39; };<br>    });<br>    <br>    expect(result.current.data).toEqual({ message: &#39;test&#39; });<br>  });<br>});</pre><h4>Integration Testing</h4><pre>// Testing NotificationSystem component<br>import { render, screen, fireEvent, waitFor } from &#39;@testing-library/react&#39;;<br>import NotificationSystem from &#39;../components/NotificationSystem&#39;;<br><br>// Mock the useSSE hook<br>jest.mock(&#39;../hooks/useSSE&#39;, () =&gt; ({<br>  useSSE: jest.fn()<br>}));<br><br>describe(&#39;NotificationSystem&#39;, () =&gt; {<br>  test(&#39;displays notifications when received&#39;, async () =&gt; {<br>    const mockData = {<br>      type: &#39;notification&#39;,<br>      message: &#39;Test notification&#39;,<br>      id: &#39;123&#39;,<br>      timestamp: new Date().toISOString()<br>    };<br>    <br>    useSSE.mockReturnValue({<br>      data: mockData,<br>      error: null,<br>      isConnected: true<br>    });<br>    <br>    render(&lt;NotificationSystem /&gt;);<br>    <br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(&#39;Test notification&#39;)).toBeInTheDocument();<br>    });<br>  });<br>  <br>  test(&#39;marks notification as read&#39;, async () =&gt; {<br>    // Test implementation<br>  });<br>});</pre><h3>8. Conclusion</h3><p>SSE is an extremely useful technology for implementing real-time notifications, live feeds, and real-time updates. Especially when only unidirectional communication is needed, it can be a simpler and more efficient choice than WebSocket.</p><p>The combination of SSE’s simplicity and React’s component-based architecture provides an excellent foundation for building responsive, real-time user interfaces. The automatic reconnection features and HTTP compatibility make SSE particularly attractive for production applications where reliability and ease of deployment are important considerations.</p><p>Key takeaways from implementing SSE with React:</p><p><strong>Simplicity First:</strong> SSE’s straightforward implementation makes it ideal for many real-time scenarios without the complexity of WebSocket protocols.</p><p><strong>Robust Error Handling:</strong> Implementing proper reconnection logic, exponential backoff, and graceful degradation ensures a reliable user experience.</p><p><strong>Performance Optimization:</strong> Connection pooling, message batching, and proper resource cleanup are essential for scalable applications.</p><p><strong>Production Readiness:</strong> Consider security, monitoring, rate limiting, and load balancing when deploying to production environments.</p><p><strong>Testing Strategy:</strong> Comprehensive testing of both the SSE connection logic and UI components ensures reliable functionality.</p><p>Whether you’re building a notification system, live dashboard, real-time chat, or collaborative tool, SSE with React offers a robust, scalable solution that balances simplicity with powerful real-time capabilities. The patterns and techniques covered in this guide provide a solid foundation for building production-ready real-time applications that deliver excellent user experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a999bb983d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Chat Application with React and Socket.io]]></title>
            <link>https://medium.com/@dlrnjstjs/building-a-real-time-chat-application-with-react-and-socket-io-078d69d4dd6e?source=rss-f003027f6cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/078d69d4dd6e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Logan Lee]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 14:52:21 GMT</pubDate>
            <atom:updated>2025-09-17T14:52:21.560Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-time communication has become the backbone of modern web applications. From messaging platforms like Discord and Slack to collaborative tools and gaming applications, the ability to send and receive data instantly has transformed user expectations. Today, I’ll walk you through building a complete real-time chat application using React and Socket.io.</p><h3>1. Why Socket.io Over Native WebSockets?</h3><p>Before diving into the implementation, let’s address the elephant in the room: why choose Socket.io when native WebSockets are available?</p><h4><strong>Native WebSockets</strong> provide a lightweight, standardized protocol for real-time communication. However, they come with limitations:</h4><ul><li>Limited browser compatibility (especially older browsers)</li><li>No built-in room management</li><li>Manual implementation of reconnection logic</li><li>Basic error handling</li></ul><h4><strong>Socket.io</strong>, on the other hand, offers:</h4><ul><li><strong>Automatic fallback support</strong> for browsers that don’t support WebSockets</li><li><strong>Built-in room management</strong> for organizing users into different chat channels</li><li><strong>Automatic reconnection</strong> with exponential backoff</li><li><strong>Event-driven architecture</strong> that simplifies complex real-time interactions</li><li><strong>Broadcasting capabilities</strong> with sophisticated targeting</li></ul><p>For chat applications, these features make Socket.io the clear winner despite its slightly larger bundle size.</p><h4>Project Architecture Overview</h4><p>Our chat application will consist of two main parts:</p><ol><li><strong>Node.js server</strong> with Express and Socket.io handling real-time connections</li><li><strong>React client</strong> with Socket.io-client for the user interface</li></ol><p>The server will manage user connections, room assignments, and message broadcasting, while the client will handle the user interface and real-time updates.</p><h3>2. Setting Up the Development Environment</h3><p>Let’s start by creating our server and client projects:</p><h4>Server Setup</h4><pre>mkdir chat-app-server<br>cd chat-app-server<br>npm init -y<br>npm install express socket.io cors<br>npm install -D nodemon</pre><h4>Client Setup</h4><p>Create a server.js file in your server directory:</p><pre>const express = require(&#39;express&#39;);<br>const http = require(&#39;http&#39;);<br>const socketIo = require(&#39;socket.io&#39;);<br>const cors = require(&#39;cors&#39;);<br><br>// Initialize Express application<br>const app = express();<br>const server = http.createServer(app);<br><br>// Configure CORS for cross-origin requests<br>app.use(cors({<br>  origin: &quot;http://localhost:3000&quot;,<br>  credentials: true<br>}));<br><br>// Initialize Socket.io with CORS configuration<br>const io = socketIo(server, {<br>  cors: {<br>    origin: &quot;http://localhost:3000&quot;,<br>    methods: [&quot;GET&quot;, &quot;POST&quot;],<br>    credentials: true<br>  }<br>});<br><br>// In-memory storage for connected users<br>let users = {};<br><br>// Handle client connections<br>io.on(&#39;connection&#39;, (socket) =&gt; {<br>  console.log(&#39;New user connected:&#39;, socket.id);<br><br>  // Handle user joining a room<br>  socket.on(&#39;join&#39;, (userData) =&gt; {<br>    // Store user information with socket ID as key<br>    users[socket.id] = {<br>      id: socket.id,<br>      name: userData.name,<br>      room: userData.room<br>    };<br><br>    // Join the specified room<br>    socket.join(userData.room);<br><br>    // Notify other users in the room about the new user<br>    socket.to(userData.room).emit(&#39;userJoined&#39;, {<br>      message: `${userData.name} has joined the chat`,<br>      user: users[socket.id]<br>    });<br><br>    // Send updated user list to all users in the room<br>    const roomUsers = Object.values(users).filter(user =&gt; user.room === userData.room);<br>    io.to(userData.room).emit(&#39;roomUsers&#39;, roomUsers);<br>  });<br><br>  // Handle message broadcasting<br>  socket.on(&#39;sendMessage&#39;, (messageData) =&gt; {<br>    const user = users[socket.id];<br>    <br>    if (user) {<br>      // Create complete message object<br>      const message = {<br>        id: Date.now(),<br>        text: messageData.text,<br>        user: user.name,<br>        timestamp: new Date().toISOString(),<br>        room: user.room<br>      };<br><br>      // Broadcast message to all users in the same room<br>      io.to(user.room).emit(&#39;message&#39;, message);<br>    }<br>  });<br><br>  // Handle user disconnection<br>  socket.on(&#39;disconnect&#39;, () =&gt; {<br>    const user = users[socket.id];<br>    <br>    if (user) {<br>      // Notify other users about disconnection<br>      socket.to(user.room).emit(&#39;userLeft&#39;, {<br>        message: `${user.name} has left the chat`<br>      });<br><br>      // Remove user from storage<br>      delete users[socket.id];<br><br>      // Update room user list<br>      const roomUsers = Object.values(users).filter(u =&gt; u.room === user.room);<br>      io.to(user.room).emit(&#39;roomUsers&#39;, roomUsers);<br>    }<br>    <br>    console.log(&#39;User disconnected:&#39;, socket.id);<br>  });<br>});<br><br>// Start the server<br>const PORT = process.env.PORT || 5000;<br>server.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><p><strong>Code Breakdown:</strong></p><ol><li><strong>Express and Socket.io Setup</strong>: We create an HTTP server using Express and attach Socket.io to it. This allows us to serve both HTTP requests and WebSocket connections from the same port.</li><li><strong>CORS Configuration</strong>: Cross-Origin Resource Sharing (CORS) is configured to allow our React app running on port 3000 to communicate with our server on port 5000.</li><li><strong>User Management</strong>: The users object acts as an in-memory database to track connected users. In production, you&#39;d want to use a proper database like Redis for this.</li><li><strong>Room System</strong>: Socket.io’s join() method allows users to be grouped into different chat rooms, enabling multiple concurrent conversations.</li><li><strong>Event Handling</strong>: We handle three main events — user joining, message sending, and user disconnection — each with specific business logic.</li></ol><h3>3. Creating the Socket.io Client Connection</h3><p>First, let’s create a dedicated module for socket management in src/socket.js:</p><pre>import io from &#39;socket.io-client&#39;;<br><br>// Use environment variable for production deployment<br>const SOCKET_URL = process.env.REACT_APP_SOCKET_URL || &#39;http://localhost:5000&#39;;<br><br>// Create Socket.io client instance with configuration<br>export const socket = io(SOCKET_URL, {<br>  // Disable auto-connection for manual control<br>  autoConnect: false,<br>  // Reconnection settings for network reliability<br>  reconnection: true,<br>  reconnectionAttempts: 5,<br>  reconnectionDelay: 1000,<br>});<br><br>// Helper functions for connection management<br>export const connectSocket = () =&gt; {<br>  if (!socket.connected) {<br>    socket.connect();<br>  }<br>};<br><br>export const disconnectSocket = () =&gt; {<br>  if (socket.connected) {<br>    socket.disconnect();<br>  }<br>};</pre><p><strong>Key Design Decisions:</strong></p><ol><li><strong>Manual Connection Control</strong>: By setting autoConnect: false, we gain precise control over when the socket connection is established, preventing unnecessary connections before user authentication.</li><li><strong>Environment-Based Configuration</strong>: Using environment variables allows seamless transitions between development and production environments.</li><li><strong>Reconnection Strategy</strong>: The configuration includes automatic reconnection with exponential backoff, ensuring robust connectivity even with unstable networks.</li></ol><h4>Building the React Chat Interface</h4><p><strong>Main Chat Component</strong></p><p>Create src/components/Chat.js:</p><pre>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br>import { socket, connectSocket, disconnectSocket } from &#39;../socket&#39;;<br>import MessageList from &#39;./MessageList&#39;;<br>import MessageInput from &#39;./MessageInput&#39;;<br>import UserList from &#39;./UserList&#39;;<br>import &#39;./Chat.css&#39;;<br><br>const Chat = () =&gt; {<br>  // State management for chat functionality<br>  const [messages, setMessages] = useState([]);<br>  const [users, setUsers] = useState([]);<br>  const [currentUser, setCurrentUser] = useState(null);<br>  const [room, setRoom] = useState(&#39;general&#39;);<br>  const [username, setUsername] = useState(&#39;&#39;);<br>  const [isJoined, setIsJoined] = useState(false);<br>  const [isConnected, setIsConnected] = useState(false);<br><br>  // Reference for auto-scrolling to latest messages<br>  const messagesEndRef = useRef(null);<br><br>  // Set up socket event listeners on component mount<br>  useEffect(() =&gt; {<br>    // Connection status management<br>    socket.on(&#39;connect&#39;, () =&gt; {<br>      console.log(&#39;Connected to server&#39;);<br>      setIsConnected(true);<br>    });<br><br>    socket.on(&#39;disconnect&#39;, () =&gt; {<br>      console.log(&#39;Disconnected from server&#39;);<br>      setIsConnected(false);<br>    });<br><br>    // Message handling<br>    socket.on(&#39;message&#39;, (message) =&gt; {<br>      setMessages(prevMessages =&gt; [...prevMessages, message]);<br>    });<br><br>    // User join notification<br>    socket.on(&#39;userJoined&#39;, (data) =&gt; {<br>      setMessages(prevMessages =&gt; [...prevMessages, {<br>        id: Date.now(),<br>        text: data.message,<br>        user: &#39;System&#39;,<br>        timestamp: new Date().toISOString(),<br>        isSystem: true<br>      }]);<br>    });<br><br>    // User leave notification<br>    socket.on(&#39;userLeft&#39;, (data) =&gt; {<br>      setMessages(prevMessages =&gt; [...prevMessages, {<br>        id: Date.now(),<br>        text: data.message,<br>        user: &#39;System&#39;,<br>        timestamp: new Date().toISOString(),<br>        isSystem: true<br>      }]);<br>    });<br><br>    // Room user list updates<br>    socket.on(&#39;roomUsers&#39;, (roomUsers) =&gt; {<br>      setUsers(roomUsers);<br>    });<br><br>    // Cleanup on component unmount<br>    return () =&gt; {<br>      socket.off(&#39;connect&#39;);<br>      socket.off(&#39;disconnect&#39;);<br>      socket.off(&#39;message&#39;);<br>      socket.off(&#39;userJoined&#39;);<br>      socket.off(&#39;userLeft&#39;);<br>      socket.off(&#39;roomUsers&#39;);<br>      disconnectSocket();<br>    };<br>  }, []);<br><br>  // Auto-scroll to bottom when new messages arrive<br>  useEffect(() =&gt; {<br>    scrollToBottom();<br>  }, [messages]);<br><br>  const scrollToBottom = () =&gt; {<br>    messagesEndRef.current?.scrollIntoView({ behavior: &quot;smooth&quot; });<br>  };<br><br>  // Handle room entry<br>  const handleJoin = () =&gt; {<br>    if (username.trim()) {<br>      connectSocket();<br>      <br>      const userData = {<br>        name: username.trim(),<br>        room: room<br>      };<br>      <br>      setCurrentUser(userData);<br>      socket.emit(&#39;join&#39;, userData);<br>      setIsJoined(true);<br>    }<br>  };<br><br>  // Handle message sending<br>  const handleSendMessage = (messageText) =&gt; {<br>    if (messageText.trim() &amp;&amp; isConnected) {<br>      socket.emit(&#39;sendMessage&#39;, {<br>        text: messageText.trim()<br>      });<br>    }<br>  };<br><br>  // Handle leaving the chat room<br>  const handleLeave = () =&gt; {<br>    disconnectSocket();<br>    setIsJoined(false);<br>    setCurrentUser(null);<br>    setMessages([]);<br>    setUsers([]);<br>    setUsername(&#39;&#39;);<br>  };<br><br>  // Render login form if not joined<br>  if (!isJoined) {<br>    return (<br>      &lt;div className=&quot;login-container&quot;&gt;<br>        &lt;div className=&quot;login-form&quot;&gt;<br>          &lt;h2&gt;Join Chat Room&lt;/h2&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            placeholder=&quot;Enter your username&quot;<br>            value={username}<br>            onChange={(e) =&gt; setUsername(e.target.value)}<br>            onKeyPress={(e) =&gt; e.key === &#39;Enter&#39; &amp;&amp; handleJoin()}<br>          /&gt;<br>          &lt;select<br>            value={room}<br>            onChange={(e) =&gt; setRoom(e.target.value)}<br>          &gt;<br>            &lt;option value=&quot;general&quot;&gt;General&lt;/option&gt;<br>            &lt;option value=&quot;tech&quot;&gt;Technology&lt;/option&gt;<br>            &lt;option value=&quot;random&quot;&gt;Random&lt;/option&gt;<br>          &lt;/select&gt;<br>          &lt;button onClick={handleJoin} disabled={!username.trim()}&gt;<br>            Join Chat<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  // Render main chat interface<br>  return (<br>    &lt;div className=&quot;chat-container&quot;&gt;<br>      &lt;div className=&quot;chat-header&quot;&gt;<br>        &lt;h2&gt;#{room} Chat Room&lt;/h2&gt;<br>        &lt;div className=&quot;connection-status&quot;&gt;<br>          &lt;span className={`status ${isConnected ? &#39;connected&#39; : &#39;disconnected&#39;}`}&gt;<br>            {isConnected ? &#39;Connected&#39; : &#39;Disconnected&#39;}<br>          &lt;/span&gt;<br>          &lt;button onClick={handleLeave} className=&quot;leave-button&quot;&gt;<br>            Leave<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;chat-body&quot;&gt;<br>        &lt;div className=&quot;messages-section&quot;&gt;<br>          &lt;MessageList <br>            messages={messages} <br>            currentUser={currentUser?.name}<br>          /&gt;<br>          &lt;div ref={messagesEndRef} /&gt;<br>        &lt;/div&gt;<br>        <br>        &lt;div className=&quot;users-section&quot;&gt;<br>          &lt;UserList users={users} /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;MessageInput <br>        onSendMessage={handleSendMessage}<br>        disabled={!isConnected}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Chat;</pre><p><strong>Architecture Highlights:</strong></p><ol><li><strong>State Management</strong>: The component uses React hooks to manage complex state including messages, users, connection status, and UI state.</li><li><strong>Event Driven Updates</strong>: Socket.io events directly update React state, creating a reactive UI that responds to real-time changes.</li><li><strong>Auto-scrolling</strong>: The messagesEndRef ensures users always see the latest messages without manual scrolling.</li><li><strong>Connection Resilience</strong>: The UI reflects connection status and gracefully handles disconnections.</li></ol><h4>Message List Component</h4><p>Create src/components/MessageList.js:</p><pre>import React from &#39;react&#39;;<br><br>const MessageList = ({ messages, currentUser }) =&gt; {<br>  // Format timestamp for display<br>  const formatTime = (timestamp) =&gt; {<br>    const date = new Date(timestamp);<br>    return date.toLocaleTimeString([], { <br>      hour: &#39;2-digit&#39;, <br>      minute: &#39;2-digit&#39; <br>    });<br>  };<br><br>  return (<br>    &lt;div className=&quot;message-list&quot;&gt;<br>      {messages.map((message) =&gt; (<br>        &lt;div <br>          key={message.id} <br>          className={`message ${<br>            message.isSystem <br>              ? &#39;system-message&#39; <br>              : message.user === currentUser <br>                ? &#39;own-message&#39; <br>                : &#39;other-message&#39;<br>          }`}<br>        &gt;<br>          {!message.isSystem &amp;&amp; (<br>            &lt;div className=&quot;message-header&quot;&gt;<br>              &lt;span className=&quot;message-user&quot;&gt;{message.user}&lt;/span&gt;<br>              &lt;span className=&quot;message-time&quot;&gt;{formatTime(message.timestamp)}&lt;/span&gt;<br>            &lt;/div&gt;<br>          )}<br>          &lt;div className=&quot;message-text&quot;&gt;<br>            {message.text}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default MessageList;</pre><p><strong>Component Features:</strong></p><ol><li><strong>Message Differentiation</strong>: Visual distinction between own messages, other users’ messages, and system notifications.</li><li><strong>Time Formatting</strong>: User-friendly timestamp display using locale-appropriate formatting.</li><li><strong>Conditional Rendering</strong>: System messages have different styling and don’t show user information.</li></ol><h4>Message Input Component</h4><p>Create src/components/MessageInput.js:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const MessageInput = ({ onSendMessage, disabled }) =&gt; {<br>  const [message, setMessage] = useState(&#39;&#39;);<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    if (message.trim()) {<br>      onSendMessage(message);<br>      setMessage(&#39;&#39;); // Clear input after sending<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit} className=&quot;message-input-form&quot;&gt;<br>      &lt;div className=&quot;input-container&quot;&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={message}<br>          onChange={(e) =&gt; setMessage(e.target.value)}<br>          placeholder={disabled ? &quot;Connecting...&quot; : &quot;Type a message...&quot;}<br>          disabled={disabled}<br>          maxLength={500} // Prevent overly long messages<br>        /&gt;<br>        &lt;button <br>          type=&quot;submit&quot; <br>          disabled={disabled || !message.trim()}<br>          className=&quot;send-button&quot;<br>        &gt;<br>          Send<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default MessageInput;</pre><p><strong>User Experience Considerations:</strong></p><ol><li><strong>Form Handling</strong>: Proper form submission allows users to send messages by pressing Enter.</li><li><strong>Input Validation</strong>: The send button is disabled when there’s no content or when disconnected.</li><li><strong>Character Limits</strong>: Preventing extremely long messages that could break the UI or overwhelm other users.</li></ol><h4>User List Component</h4><p>Create src/components/UserList.js:</p><pre>import React from &#39;react&#39;;<br><br>const UserList = ({ users }) =&gt; {<br>  return (<br>    &lt;div className=&quot;user-list&quot;&gt;<br>      &lt;h3&gt;Online Users ({users.length})&lt;/h3&gt;<br>      &lt;div className=&quot;users&quot;&gt;<br>        {users.map((user) =&gt; (<br>          &lt;div key={user.id} className=&quot;user-item&quot;&gt;<br>            &lt;div className=&quot;user-avatar&quot;&gt;<br>              {user.name.charAt(0).toUpperCase()}<br>            &lt;/div&gt;<br>            &lt;span className=&quot;user-name&quot;&gt;{user.name}&lt;/span&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UserList;</pre><h3>4. Advanced Features Implementation</h3><h4>Typing Indicators</h4><p>Add typing indicators to show when users are composing messages:</p><pre>// In MessageInput component<br>const [isTyping, setIsTyping] = useState(false);<br>const typingTimeoutRef = useRef(null);<br><br>const handleInputChange = (e) =&gt; {<br>  setMessage(e.target.value);<br>  <br>  // Start typing indicator<br>  if (!isTyping) {<br>    setIsTyping(true);<br>    socket.emit(&#39;typing&#39;, { isTyping: true });<br>  }<br>  <br>  // Clear existing timeout and set new one<br>  clearTimeout(typingTimeoutRef.current);<br>  typingTimeoutRef.current = setTimeout(() =&gt; {<br>    setIsTyping(false);<br>    socket.emit(&#39;typing&#39;, { isTyping: false });<br>  }, 1000);<br>};</pre><p><strong>Implementation Notes:</strong></p><ol><li><strong>Debouncing</strong>: The typing indicator uses a timeout to prevent excessive server communication.</li><li><strong>State Management</strong>: Tracks typing state to avoid sending duplicate typing events.</li><li><strong>Cleanup</strong>: Proper timeout cleanup prevents memory leaks.</li></ol><h4>Message Status Indicators</h4><p>Implement read receipts and delivery status:</p><pre>// Server-side: Handle message read status<br>socket.on(&#39;messageRead&#39;, (messageId) =&gt; {<br>  socket.to(users[socket.id].room).emit(&#39;messageReadUpdate&#39;, {<br>    messageId,<br>    readBy: users[socket.id].name<br>  });<br>});</pre><h4>File Sharing Capability</h4><p>Add support for image and file sharing:</p><pre>// File upload handler<br>const handleFileUpload = (file) =&gt; {<br>  // Check file size and type<br>  if (file.size &gt; 5 * 1024 * 1024) { // 5MB limit<br>    alert(&#39;File too large. Maximum size is 5MB.&#39;);<br>    return;<br>  }<br><br>  const reader = new FileReader();<br>  reader.onload = (e) =&gt; {<br>    socket.emit(&#39;sendFile&#39;, {<br>      fileName: file.name,<br>      fileData: e.target.result,<br>      fileType: file.type,<br>      fileSize: file.size<br>    });<br>  };<br>  reader.readAsDataURL(file);<br>};</pre><h3>5. Styling with CSS</h3><p>Create a responsive design in src/components/Chat.css:</p><pre>/* Main container with flexbox layout */<br>.chat-container {<br>  display: flex;<br>  flex-direction: column;<br>  height: 100vh;<br>  max-width: 1200px;<br>  margin: 0 auto;<br>  border: 1px solid #e1e5e9;<br>  border-radius: 8px;<br>  overflow: hidden;<br>  font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, &#39;Roboto&#39;, sans-serif;<br>}<br><br>/* Header with connection status */<br>.chat-header {<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>  padding: 1rem 1.5rem;<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>  color: white;<br>  box-shadow: 0 2px 4px rgba(0,0,0,0.1);<br>}<br><br>.connection-status {<br>  display: flex;<br>  align-items: center;<br>  gap: 1rem;<br>}<br><br>.status {<br>  padding: 0.25rem 0.75rem;<br>  border-radius: 12px;<br>  font-size: 0.8rem;<br>  font-weight: 600;<br>  text-transform: uppercase;<br>  letter-spacing: 0.5px;<br>}<br><br>.status.connected {<br>  background-color: rgba(16, 185, 129, 0.2);<br>  color: #10b981;<br>  border: 1px solid #10b981;<br>}<br><br>.status.disconnected {<br>  background-color: rgba(239, 68, 68, 0.2);<br>  color: #ef4444;<br>  border: 1px solid #ef4444;<br>}<br><br>/* Chat body with sidebar */<br>.chat-body {<br>  display: flex;<br>  flex: 1;<br>  overflow: hidden;<br>}<br><br>.messages-section {<br>  flex: 1;<br>  display: flex;<br>  flex-direction: column;<br>  overflow: hidden;<br>  background-color: #f8fafc;<br>}<br><br>.users-section {<br>  width: 280px;<br>  border-left: 1px solid #e1e5e9;<br>  background-color: #ffffff;<br>}<br><br>/* Message styling with modern chat bubbles */<br>.message-list {<br>  flex: 1;<br>  padding: 1.5rem;<br>  overflow-y: auto;<br>  background-color: #f8fafc;<br>}<br><br>.message {<br>  margin-bottom: 1.5rem;<br>  padding: 1rem 1.25rem;<br>  border-radius: 18px;<br>  max-width: 75%;<br>  position: relative;<br>  animation: messageSlide 0.3s ease-out;<br>}<br><br>@keyframes messageSlide {<br>  from {<br>    opacity: 0;<br>    transform: translateY(10px);<br>  }<br>  to {<br>    opacity: 1;<br>    transform: translateY(0);<br>  }<br>}<br><br>.own-message {<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>  color: white;<br>  margin-left: auto;<br>  text-align: right;<br>  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.3);<br>}<br><br>.other-message {<br>  background-color: #ffffff;<br>  color: #374151;<br>  border: 1px solid #e5e7eb;<br>  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);<br>}<br><br>.system-message {<br>  background-color: #fef3c7;<br>  color: #92400e;<br>  text-align: center;<br>  margin: 1rem auto;<br>  max-width: 80%;<br>  font-style: italic;<br>  border: 1px solid #fbbf24;<br>}<br><br>/* Message header styling */<br>.message-header {<br>  display: flex;<br>  justify-content: space-between;<br>  margin-bottom: 0.5rem;<br>  font-size: 0.75rem;<br>  opacity: 0.8;<br>  font-weight: 500;<br>}<br><br>.message-user {<br>  font-weight: 600;<br>}<br><br>.message-time {<br>  font-size: 0.7rem;<br>}<br><br>/* Input area with modern styling */<br>.message-input-form {<br>  padding: 1.5rem;<br>  border-top: 1px solid #e1e5e9;<br>  background-color: #ffffff;<br>}<br><br>.input-container {<br>  display: flex;<br>  gap: 0.75rem;<br>  align-items: flex-end;<br>}<br><br>.input-container input {<br>  flex: 1;<br>  padding: 0.875rem 1.125rem;<br>  border: 1px solid #d1d5db;<br>  border-radius: 24px;<br>  font-size: 0.95rem;<br>  outline: none;<br>  transition: all 0.2s ease;<br>  background-color: #f9fafb;<br>}<br><br>.input-container input:focus {<br>  border-color: #667eea;<br>  background-color: #ffffff;<br>  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);<br>}<br><br>.send-button {<br>  padding: 0.875rem 1.5rem;<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>  color: white;<br>  border: none;<br>  border-radius: 24px;<br>  cursor: pointer;<br>  font-size: 0.9rem;<br>  font-weight: 600;<br>  transition: all 0.2s ease;<br>  min-width: 80px;<br>}<br><br>.send-button:hover:not(:disabled) {<br>  transform: translateY(-1px);<br>  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);<br>}<br><br>.send-button:disabled {<br>  background: #9ca3af;<br>  cursor: not-allowed;<br>  transform: none;<br>  box-shadow: none;<br>}<br><br>/* User list with modern avatars */<br>.user-list {<br>  padding: 1.5rem;<br>}<br><br>.user-list h3 {<br>  margin-bottom: 1rem;<br>  color: #374151;<br>  font-size: 0.9rem;<br>  font-weight: 600;<br>  text-transform: uppercase;<br>  letter-spacing: 0.5px;<br>}<br><br>.user-item {<br>  display: flex;<br>  align-items: center;<br>  gap: 0.75rem;<br>  padding: 0.75rem;<br>  margin-bottom: 0.5rem;<br>  border-radius: 12px;<br>  background-color: #f8fafc;<br>  transition: background-color 0.2s ease;<br>}<br><br>.user-item:hover {<br>  background-color: #e2e8f0;<br>}<br><br>.user-avatar {<br>  width: 36px;<br>  height: 36px;<br>  border-radius: 50%;<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>  color: white;<br>  display: flex;<br>  align-items: center;<br>  justify-content: center;<br>  font-weight: 600;<br>  font-size: 0.9rem;<br>}<br><br>.user-name {<br>  font-weight: 500;<br>  color: #374151;<br>}<br><br>/* Login form with modern styling */<br>.login-container {<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  height: 100vh;<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>}<br><br>.login-form {<br>  background: white;<br>  padding: 2.5rem;<br>  border-radius: 16px;<br>  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);<br>  min-width: 320px;<br>  backdrop-filter: blur(10px);<br>}<br><br>.login-form h2 {<br>  text-align: center;<br>  margin-bottom: 2rem;<br>  color: #1f2937;<br>  font-weight: 700;<br>}<br><br>.login-form input,<br>.login-form select {<br>  width: 100%;<br>  padding: 0.875rem 1.125rem;<br>  margin-bottom: 1.25rem;<br>  border: 1px solid #d1d5db;<br>  border-radius: 8px;<br>  font-size: 0.95rem;<br>  transition: border-color 0.2s ease;<br>  background-color: #f9fafb;<br>}<br><br>.login-form input:focus,<br>.login-form select:focus {<br>  outline: none;<br>  border-color: #667eea;<br>  background-color: white;<br>  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);<br>}<br><br>.login-form button {<br>  width: 100%;<br>  padding: 0.875rem;<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>  color: white;<br>  border: none;<br>  border-radius: 8px;<br>  font-size: 0.95rem;<br>  font-weight: 600;<br>  cursor: pointer;<br>  transition: all 0.2s ease;<br>}<br><br>.login-form button:hover:not(:disabled) {<br>  transform: translateY(-1px);<br>  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);<br>}<br><br>.login-form button:disabled {<br>  background: #9ca3af;<br>  cursor: not-allowed;<br>  transform: none;<br>}<br><br>/* Responsive design */<br>@media (max-width: 768px) {<br>  .chat-body {<br>    flex-direction: column;<br>  }<br>  <br>  .users-section {<br>    width: 100%;<br>    max-height: 150px;<br>    overflow-y: auto;<br>  }<br>  <br>  .message {<br>    max-width: 85%;<br>  }<br>  <br>  .login-form {<br>    margin: 1rem;<br>    min-width: auto;<br>  }<br>}</pre><h3>6. Production Deployment Considerations</h3><h4>Environment Configuration</h4><p>Create environment-specific configurations:</p><pre>// production.env<br>REACT_APP_SOCKET_URL=https://your-chat-server.herokuapp.com<br>NODE_ENV=production<br><br>// development.env<br>REACT_APP_SOCKET_URL=http://localhost:5000<br>NODE_ENV=development</pre><h3>7. Performance Optimizations</h3><ol><li><strong>Component Memoization:</strong></li></ol><pre>import React, { memo } from &#39;react&#39;;<br><br>const MessageList = memo(({ messages, currentUser }) =&gt; {<br>  // Component implementation<br>});</pre><p>2.<strong> Message Virtualization:</strong> For handling thousands of messages efficiently:</p><pre>npm install react-window react-window-infinite-loader</pre><p>3.<strong> Image Optimization:</strong> Implement image compression for file uploads:</p><pre>const compressImage = (file, maxWidth = 800, quality = 0.8) =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    const canvas = document.createElement(&#39;canvas&#39;);<br>    const ctx = canvas.getContext(&#39;2d&#39;);<br>    const img = new Image();<br>    <br>    img.onload = () =&gt; {<br>      canvas.width = maxWidth;<br>      canvas.height = (img.height * maxWidth) / img.width;<br>      <br>      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);<br>      canvas.toBlob(resolve, &#39;image/jpeg&#39;, quality);<br>    };<br>    <br>    img.src = URL.createObjectURL(file);<br>  });<br>};</pre><h3>8. Security Implementation</h3><ol><li><strong>Input Sanitization:</strong></li></ol><pre>npm install dompurify</pre><pre>import DOMPurify from &#39;dompurify&#39;;<br><br>const sanitizeMessage = (message) =&gt; {<br>  return DOMPurify.sanitize(message, { ALLOWED_TAGS: [] });<br>};</pre><p>2. <strong>Rate Limiting:</strong></p><pre>// Server-side rate limiting<br>const rateLimit = require(&#39;express-rate-limit&#39;);<br><br>const messageLimit = rateLimit({<br>  windowMs: 60 * 1000, // 1 minute<br>  max: 30, // 30 messages per minute<br>  message: &#39;Too many messages, please slow down&#39;<br>});<br><br>app.use(&#39;/api&#39;, messageLimit);</pre><p>3.<strong> JWT Authentication:</strong></p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br><br>// Verify token middleware<br>const verifyToken = (socket, next) =&gt; {<br>  const token = socket.handshake.auth.token;<br>  jwt.verify(token, process.env.JWT_SECRET, (err, decoded) =&gt; {<br>    if (err) return next(new Error(&#39;Authentication error&#39;));<br>    socket.userId = decoded.userId;<br>    next();<br>  });<br>};<br><br>io.use(verifyToken);</pre><h3>9. Conclusion</h3><p>Building a real-time chat application with React and Socket.io demonstrates the power of modern web technologies for creating engaging, interactive experiences. We’ve covered:</p><ul><li><strong>Real-time Communication</strong>: Bidirectional communication using Socket.io</li><li><strong>Room Management</strong>: Multiple chat channels with user segregation</li><li><strong>Connection Resilience</strong>: Automatic reconnection and status management</li><li><strong>Modern UI/UX</strong>: Responsive design with smooth animations</li><li><strong>Scalability Considerations</strong>: Performance optimizations and security measures</li></ul><p>The architecture we’ve built provides a solid foundation that can be extended with features like:</p><ul><li>Message persistence with databases</li><li>User authentication and profiles</li><li>File sharing and media support</li><li>Push notifications</li><li>Message encryption</li><li>Mobile app versions</li></ul><p>Socket.io’s robust feature set makes it ideal for real-time applications beyond chat — consider it for collaborative tools, live gaming, financial dashboards, or any application requiring instant data updates.</p><p>The complete source code provides a production-ready starting point that you can customize and scale according to your specific requirements. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=078d69d4dd6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>