Multiple Suspense declaration in React

For example I have this declaration:

Scenario 1:

const ComponentA = lazy(() => import('pages/ComponentA'));
const ComponentB = lazy(() => import('pages/ComponentB'));

<Router>
  <Switch>
     <Suspense fallback={'loading...'}>
       <Route path="/A" component={ComponentA} exact/>
       <Route path="/B" component={ComponentB} exact/> 
     </Suspense>
  </Switch>
</Router>

This scenario is fine if the loading dependency of ComponentA is just 1.

But for Scenario 2: what if I have multiple dependency in ComponentA?

Code 2

import Dependency1 from 'component/dependency1';
import Dependency2 from 'component/dependency2';

const ComponentA = () => {
   return (
     <div>
       <Dependency1/>
       <Dependency2/>
     </div>
   );
}

is it okay to separate the Suspense declaration for each Dependency? like this:

Code 3

 const Dependency1 = lazy(() => import('component/dependency1'));
 const Dependency2 = lazy(() => import('component/dependency2'));

 const ComponentA = () => {
   return (
     <div>
       <Suspense fallback={'Loading Dependency1'}>
         <Dependency1/>
       <Suspense/>
       <Suspense fallback={'Loading Dependency2'}>
        <Dependency2/>
       <Suspense/>
     </div>
   );
}

then I’ll remove the Suspense declaration in the Router file…

My Question is it okay to have a structure like Code 3 since I want to have a multiple separate loading indicator in each dependency?

Is there any downside of this approach like performance or multiple request in each sub-component since I’m code splitting each Dependency?

Answer

Sure, this approach is totally fine, especially when you want to have different loaders for different components.

There is small downside you mentioned, multiple request for each lazy component, but it would not matter too much. If some components are conditional it would even be better to use multiple loaders since some users might not even need Dependency2 at all, for example.

One thing to consider is “loaders clutter”. It might be better from UX perspective to have skeleton page instead of 4-5 different loaders which are going to load separately and page might even jump unexpectedly.

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .