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)