5kdk Blog

website·Indexed 31 days ago

https://5kdk.github.io

A technical blog featuring practical development records and deep dives into frontend engineering. Topics include Next.js caching strategies, TanStack React Query patterns, TypeScript utility types, ESLint static analysis, and React performance optimization using hooks like useMemo and useCallback. The blog also covers real-world troubleshooting with Firebase, PortOne payment integration, and UX strategies for frontend development.

Tokens
18.5K
Snippets
96
Records
133
Agent score
75%

What's inside 5kdk Blog

  1. Overview of Core Web Vitals and their impact

    Core Web Vitals are a subset of Web Vitals created by Google to measure the user experience of a page based on loading, interactivity, and visual stability. These metrics are used as ranking factors in Google's search algorithm, meaning poor scores can negatively impact search engine visibility and business traffic. Performance improvements are linked to higher retention and conversion rates (e.g., Pinterest saw a 15% increase in search traffic and sign-ups after reducing perceived latency by 40%).

    The three primary metrics are:

    • LCP (Largest Contentful Paint): Measures loading performance.
    • FID (First Input Delay): Measures interactivity/responsiveness.
    • CLS (Cumulative Layout Shift): Measures visual stability.
  2. Understand how ESLint performs static code analysis

    ESLint analyzes code through a four-step process:

    1. Reads JavaScript code as a string.
    2. Uses a parser (default is espree) to structure the code.
    3. Generates an Abstract Syntax Tree (AST) from the structured code and compares it against defined rules.
    4. Reports violations or applies fixes based on the rule comparisons.

    For TypeScript, ESLint uses @typescript-eslint/typescript-estree, which is based on espree.

  3. Understand the Stale-While-Revalidate (SWR) caching strategy

    Stale-While-Revalidate is a strategy that improves user experience and reduces server load by providing cached (stale) data immediately while simultaneously fetching an updated version in the background. Once the fresh data is retrieved, the cache is updated for subsequent requests.
  4. Automatic font optimization in Next.js

    Next.js automatically optimizes web fonts by inlining font CSS during the build process. This eliminates additional network round-trips to fetch font declarations, improving First Contentful Paint (FCP) and Largest Contentful Paint (LCP).
  5. Lazy load React components using next/dynamic

    Use next/dynamic to load React components only when they are needed. This is particularly effective for components like modals that are not visible on the initial page load. Setting ssr: false prevents the component from being rendered on the server, further reducing the initial payload.
    import dynamic from 'next/dynamic';
    
    // Dynamically import the component
    const CodeSampleModal = dynamic(() => import('../components/CodeSampleModal'), {
      ssr: false,
    });
    
    // Render conditionally to trigger the JS request only when isModalOpen is true
    {isModalOpen && (
      <CodeSampleModal
        isOpen={isModalOpen}
        closeModal={() => setIsModalOpen(false)}
      />
    )}
    
  6. Perform on-demand cache revalidation using revalidateTag

    Use revalidateTag to purge cached data associated with a specific tag. This is essential for scenarios like admin updates or webhooks where data must be updated immediately. Setting { expire: 0 } ensures that the next request does not show stale values. If a small amount of stale-while-revalidate is acceptable, you can use revalidateTag(tag, "max") to mark the data as stale and trigger a background update on the next visit.
    import { revalidateTag } from "next/cache";
    import { NextResponse } from "next/server";
    
    export async function POST(request: Request) {
      const { type, id, year, month } = await request.json();
    
      if (type === "schedule") {
        // Purge specific tags to ensure fresh data on next request
        revalidateTag(`schedule:${year}-${month}`, { expire: 0 });
        revalidateTag(`schedule:${id}`, { expire: 0 });
        revalidateTag("schedule:list", { expire: 0 });
      }
    
      return NextResponse.json({ revalidated: true });
    }
  7. Reduce initial JS bundle size with dynamic imports

    Next.js supports ES2020 dynamic import() to load JavaScript modules on demand. This is useful for heavy third-party libraries that are only needed during specific user interactions (e.g., inside an event handler), which improves Time to Interactive (TTI) and First Input Delay (FID).
    <input
      type="text"
      onChange={async (e) => {
        const { value } = e.currentTarget;
        
        // Dynamically load libraries only when needed
        const Fuse = (await import('fuse.js')).default;
        const _ = (await import('lodash')).default;
    
        const fuse = new Fuse(countries, { keys: ['name'], threshold: 0.3 });
        const searchResult = fuse.search(value).map((result) => result.item);
        // ... handle results
        console.info({ searchedAt: _.now() });
      }}
    />
  8. Analyze Core Web Vitals impact on Google SEO ranking

    Since June 2021, Google has used specific Core Web Vitals metrics to analyze and optimize page experience for search rankings. For SEO purposes, Google treats all pages that fall within the 'Good' range for all Core Web Vitals equally. Individual scores within the 'Good' range do not provide additional ranking advantages over other pages that are also in the 'Good' range.
  9. Manually purge image caches in CloudFront and Vercel

    To ensure a new image is reflected, you must invalidate the cache at both the source (CloudFront) and the optimization layer (Vercel). Vercel's cache TTL is often based on the source's Cache-Control header, making the order of operations important.
    # Step 1: Invalidate CloudFront Cache
    aws cloudfront create-invalidation --distribution-id [DISTRIBUTION_ID] --paths "/images/banner.jpg"
    
    # Step 2: Purge Vercel CDN Cache for the source image
    vercel cache purge --srcimg https://cdn.example.com/images/banner.jpg
  10. Set up Next.js with Yarn 4 PnP (Non-Zero-Install)

    To set up a Next.js project using Yarn 4 with Plug'n'Play (PnP) while avoiding zero-install (to prevent GitHub LFS bandwidth exhaustion), follow these steps: 1. Create the app. 2. Remove default lockfiles and node_modules. 3. Enable Corepack. 4. Set Yarn to the stable version. 5. Install dependencies. 6. Configure .gitignore to exclude PnP artifacts while preserving essential Yarn configuration and releases.
    # 1. Create Next.js app
    npx create-next-app@latest
    
    # 2. Remove default artifacts
    rm -rf node_modules package-lock.json
    
    # 3. Enable Corepack
    corepack enable
    
    # 4. Set Yarn version to stable (v4)
    yarn set version stable
    
    # 5. Install dependencies
    yarn install

    .gitignore configuration

    .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions

  11. Improve page performance with lazy loading

    Use loading="lazy" to prevent the browser from wasting resources on images that are not yet in the viewport. This ensures that images are only loaded as the user scrolls down, improving initial page load speed.
    <img src="image.webp" loading="lazy" alt="Lazy loaded image" />
  12. Determine caching strategy based on data visibility

    When deciding where to cache data in a Next.js App Router application, use the criteria of whether the data is identical for all users. Public data is suitable for server-side caching, while personalized data must remain on the client side to avoid data leakage and pollution.