DEV Community

Cover image for You are using React lazy imports the wrong way.
Nikola Perišić
Nikola Perišić

Posted on • Edited on

25 7 4 4 7

You are using React lazy imports the wrong way.

I saw today in a project a lazy imports like this:

const AnimatedScore = React.lazy(() => import('../components/AnimatedScore'))
const FireworksCanvas = React.lazy(
  () => import('../components/FireworksCanvas'),
)
const Header = React.lazy(() => import('../components/Header'))
const URLForm = React.lazy(() => import('../components/URLForm'))
const LoadingErrorMessages = React.lazy(
  () => import('../components/LoadingErrorMessages'),
)
const RadarChartSection = React.lazy(
  () => import('../components/RadarChartSection'),
)
const ExceededSentences = React.lazy(
  () => import('../components/ExceededSentences'),
)
const Footer = React.lazy(() => import('../components/Footer'))
const SubHeader = React.lazy(() => import('../components/SubHeader'))
Enter fullscreen mode Exit fullscreen mode

After running npm run build, build time took 3.64 seconds!

So, what did I do to optimize this?

I switched to using the map method:

const [
  AnimatedScore,
  FireworksCanvas,
  Header,
  URLForm,
  LoadingErrorMessages,
  RadarChartSection,
  ExceededSentences,
  Footer,
  SubHeader,
] = [
  'AnimatedScore',
  'FireworksCanvas',
  'Header',
  'URLForm',
  'LoadingErrorMessages',
  'RadarChartSection',
  'ExceededSentences',
  'Footer',
  'SubHeader',
].map((component) => React.lazy(() => import(`../components/${component}.tsx`)))
Enter fullscreen mode Exit fullscreen mode

And after this modification, I got 926ms. Incredible, isn't it?

But how this this happen behind the scenes?

Explanation

Just for those who may not know, chunks are pieces of your JavaScript code that the bundler (like Vite) splits to optimize loading. Instead of loading a huge file with all your code at once, the browser loads only the necessary chunks when they are needed.

Imagine your app has three pages: Home, About, and Contact. If all the JavaScript was in one big file (bundle.js), the user would have to download everything - even the code for pages they never visit!

Instead, a bundler splits your code like this:

  • main.js → Contains shared code used across the entire app.
  • home-[hash].js → Loads only when the user visits the Home page.
  • about-[hash].js → Loads only when the user visits the About page.

Bundlers like Vite and Webpack typically add a unique hash (e.g., home-abc123.js) to filenames for better caching and cache invalidation.

And now when we know what are chunks let's see why the map methods optimizes build time.

By using map for dynamic imports, the bundler can group and optimize chunks more efficiently instead of handling each import() separately.

This means that the bundler(like Vite) can process the map in one go, creating all the required chunks more efficiently.

Summary

In short, switching from single-line lazy imports to using a map for dynamic imports optimizes the build process by:

  • Reducing redundant operations in the bundling process
  • Allowing better chunk creation and grouping
  • Enabling better parallelization of the chunk creation process
  • Optimizing chunk reuse

Code in action?

Sure, check it here (DevToPostAnalyzer.tsx) on GitHub.


Did you know about this approach to lazy imports? Share your thoughts in the comments below! 💬


Top comments (8)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

This is interesting; how is it determined to only import those components and create chunks for them? The pattern where the import has a variable in it usually makes a chunk for each possible file as it can't deterministically calculate what could be supplied. I guess that's ok if you will always lazy import everything in components, but if some were static, then it would generate some unnecessary stuff, wouldn't it?

Collapse
 
perisicnikola37 profile image
Nikola Perišić • Edited

Great question! Normally, when using import(\../components/${component}.tsx) with a variable, bundlers have to assume that any file in ../components/ could be a match, which can lead to unnecessary chunks.
However, in this case, the list of components is hardcoded inside the array, so the bundler can statically analyze all possible imports. This means it knows exactly which files will be loaded and doesn’t have to create chunks for undefined or unexpected files.

Regarding your last point - Yes, if some components were also statically imported somewhere else, this could make redundant chunks.

Collapse
 
sachin04 profile image
Sachin Yadav

Interesting!

Collapse
 
perisicnikola37 profile image
Nikola Perišić

Thanks for feedback! Glad it was helpful :)

Collapse
 
anuragdeore profile image
Anurag D

Definitely trying this, thanks for sharing

Collapse
 
perisicnikola37 profile image
Nikola Perišić • Edited

Glad it was helpful :)
If you want to see it in action feel free to check repository.
Or specifically, this file: DevToPostAnalyzer.tsx.

Retry later
Collapse
 
lebinhan profile image
Lê Bình An

This syntax is exactly what I have been looking for. Absolutely will try this, thank you for sharing mate.

Collapse
 
perisicnikola37 profile image
Nikola Perišić

You're welcome!
If you want to see it in action feel free to check repository.
Or specifically, this file: DevToPostAnalyzer.tsx.

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay