Performance Optimization

Interview Questions: Bundle Analysis, Lazy Loading, and Core Web Vitals

Q1: How do you analyze the bundle size of a Next.js application?

Tool: @next/bundle-analyzer.

Usage: It generates an interactive treemap of your client-side bundles. This helps identify large dependencies that might be accidentally included in the client bundle (instead of staying on the server).

Q2: How do you implement Lazy Loading for components?

next/dynamic: It is a composite of React.lazy() and Suspense.

import dynamic from 'next/dynamic'

const HeavyChart = dynamic(() => import('./components/HeavyChart'), {
  loading: () => 

Loading...

, ssr: false // Optional: Disable server-side rendering for this component })

This splits the component into a separate chunk that is only loaded when rendered.

Q3: How does the Script component (next/script) improve performance?

It allows you to control the loading priority of third-party scripts (like Analytics or Ads) to prevent them from blocking the main thread.

  • strategy="beforeInteractive": Load before hydration (critical scripts).
  • strategy="afterInteractive": Load immediately after hydration (default).
  • strategy="lazyOnload": Load during idle time.
  • strategy="worker": (Experimental) Load in a web worker (Partytown).

Q4: What is Image Optimization in Next.js?

next/image: The Image component automatically optimizes images on-demand.

  • Resizing: Serves correctly sized images for each device.
  • Format: Converts images to modern formats like WebP or AVIF.
  • Lazy Loading: Images are lazy-loaded by default.
  • Prevention of CLS: Enforces width and height to prevent Cumulative Layout Shift.

Q5: Explain Incremental Static Regeneration (ISR).

Concept: ISR allows you to create or update static pages after you’ve built your site.

Mechanism: You set a `revalidate` prop (in seconds) in `getStaticProps`. When a request comes in after that time, Next.js serves the stale page while generating a new one in the background for future visitors.

Benefit: Combines the speed of static sites with the freshness of dynamic rendering.