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?
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.