⚛️ React.js Intermediate

What is code splitting in React?

Why Interviewers Ask This

This question targets practical, hands-on experience with React.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Code splitting divides your JavaScript bundle into smaller chunks that are loaded on demand, reducing the initial download size and improving load time. Without code splitting, all your code is bundled into one large file that must be downloaded before the app starts. React.lazy + dynamic import: the primary way to split code in React: const Dashboard = React.lazy(() => import("./Dashboard")); — creates a separate chunk for Dashboard that only loads when it is rendered. Route-based splitting: the most impactful approach — each page/route loads its own code: in React Router, wrap lazy routes with Suspense. Component-based splitting: split large, rarely-used components (modals, charts, editors). Bundler support: webpack, Vite, and Rollup automatically create separate chunks for dynamic imports. The bundler analyzes the import graph and creates efficient chunks. Magic comments: webpack allows naming chunks: import(/* webpackChunkName: "charts" */ "./Charts"). Prefetching: use webpackPrefetch: true or Vite's prefetch to hint the browser to download chunks before they are needed.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex React.js answers easy to follow.