CodePark/ questions / Performance: code splitting
START PRACTICINGPRACTICE
Frontend question · React › Performance: code splitting

What is the difference between route-based and component-based code splitting, and how do you decide where to split?

Route-based splitting gives each page its own chunk, a separate file of code. Component-based splitting loads heavy pieces inside a page only when they are needed.

Route-based. Users only download the code for the pages they visit. Routes are natural boundaries, because users expect a short loading state when they navigate. Many frameworks and routers do this automatically.

Component-based. Good candidates are a modal, a rich text editor, a chart or a map that the user may never open.

To decide where to split:

  • Run a bundle analyzer and look for large modules not needed on first load.
  • Do not split content visible on the first screen.
  • Avoid many tiny chunks. They create request waterfalls, where one download waits for another, and extra spinners.
  • Check whether a heavy dependency can be replaced, or imported more selectively. Then tree shaking, the bundler's removal of unused code, can drop what you don't use.
  • Route-based splitting creates one chunk per page.
  • Component-based splitting targets heavy, rarely used widgets.
  • Use a bundle analyzer to find split points.
  • Do not split above-the-fold content, and do not over-split.
  • Replace heavy dependencies, or import only the parts you need.