DEV Community

Cover image for Slice Your JS: Lazy Load Components with React + Vite + Dynamic Imports
sperez927
sperez927

Posted on

Slice Your JS: Lazy Load Components with React + Vite + Dynamic Imports

๐Ÿšซ Problem: Big Bundles, Slow First Loads

Modern apps ship huge bundles. Tools like Vite and Webpack support code splitting, but it's often underused.
Here's how we dropped initial JS size by 40% by lazy-loading non-critical UI in Vite.

โœ… Solution: Dynamic Import + React.lazy

Assume we have a heavy component:

export default function Chart() {
  // big lib like recharts, visx, or d3
  return <div>Heavy Chart</div>;
}
Enter fullscreen mode Exit fullscreen mode

Instead of importing normally:

import Chart from "./Chart"

Use React.lazy:

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

Wrap it with <suspense>:

๐Ÿ“Š Result

  • Initial load time down ~40% on mobile
  • Less JS execution blocking Time to Interactive
  • Better Lighthouse scores

๐Ÿงช Vite Handle the Split

In Vite, you'll now see Chart.[hash].js as separate chunk. Automatically lazy-loaded when needed.

dist/
โ”œโ”€โ”€ index.html
โ”œโ”€โ”€ assets/
โ”‚   โ”œโ”€โ”€ main.[hash].js
โ”‚   โ””โ”€โ”€ Chart.[hash].js   โ† โœ… Lazy-loaded!
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง Bonus Tips

  • Group multiple lazy components with import() + Promise.all
  • Always provide a <fallback> for UX
  • Profile with DevTools -> Network tab -> disable cache -> reload

๐Ÿง  Takeaway

If your app feels bloated - don't refactor the whole thing. Just start lazy-loading where it hurts most.

Top comments (0)