Code Splitting & React.lazy in Interviews
⚛ ری‌اکت

Code Splitting & React.lazy in Interviews

Reduce initial bundle size with dynamic imports and Suspense boundaries.

BugCast Admin··۵ دقیقه مطالعه

Code splitting loads JavaScript on demand. React.lazy and dynamic import() are the standard SPA pattern; Next.js uses framework-level splitting automatically.

Common Interview Questions

Q: How does React.lazy work?

Answer: lazy wraps dynamic import returning a component. Must be inside Suspense boundary that handles loading state.


const Chart = lazy(() => import("./Chart"));

<Suspense fallback={<Loading />}>
  <Chart />
</Suspense>

Q: Route-based splitting?

Answer: Split at router level so each page loads its own chunk. React Router and Next.js file-based routing do this by default in modern setups.

Q: Named vs default export with lazy?

Answer: Dynamic import needs default export or .then(m => ({ default: m.Named })) transform for named exports.

Q: Preloading chunks?

Answer: Trigger import() on hover/focus of navigation links to prefetch before navigation — improves perceived performance.

Key Points for Interviews

  • Smaller initial bundle = faster TTI

  • Always pair lazy with Suspense

  • Analyze bundles with webpack-bundle-analyzer

  • SSR requires Next.js dynamic() with ssr option

  • Split at routes first, then heavy components

#code-splitting#lazy#interview

مطالب مرتبط