Rendering a list of lazy components in React

We saw in an earlier post how to render lazy-loaded components using Suspense. But what if we have a number of different components that we want to lazily load?

The answer is straightforward (barring any other interference from webpack etc..), you can just render the components in the same way you would render a list of non-lazy components, in a plain array of React components.

For example, we’ll just create a list of the components as an array and render this list in your JSX.

export default function SomeComponent() {
   const Lazy1 = lazy(() => import('./components/Lazy1');
   const Lazy2 = lazy(() => import('./components/Lazy2');
   const myLazyArray = [<Lazy1 />, <Lazy2 />];

   return (
         <h1>Here are my lazily loaded components</h1>

This approach works fine when you are not dynamically importing the components.

A dynamically lazy-loaded component would look like this:

const LazyComponent = lazy(() => import('./components/' + myVarHoldingTheComponentName);

The next article will walk through why webpack is not a fan of the above statement.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments