๐ซ 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>;
}
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!
๐ง 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)