DEV Community

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

Posted on • Edited on

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

By using a map (or reduce to generate lazy imports dynamically), you are providing the bundler with an efficient list of dependencies upfront. Instead of dealing with separate import() statements for each component, you are defining all components at once.

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

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

Top comments (4)

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.

Collapse
 
sachin04 profile image
Sachin Yadav

Interesting!

Collapse
 
perisicnikola37 profile image
Nikola Perišić

Thanks for feedback! Glad it was helpful :)