Reputation: 31
I am trying to implement lazy loading to my projects so I can lazy load routes of react-router-dom. While going through internet I noticed that there are two ways to implement it - wrapping all routes with one React.Suspense or putting every page withing its own React.Suspense. The thing is that I would like to know if there are any differences between these two methods and if there are, what are their's advantages and disadvantages?
Routes wrapped in one Suspense
<React.Suspense fallback={<p>Loading...</p>}>
<Routes>
<Route path="/" element={<MainPage/>}></Route>
<Route path="/todo/:todoID" element={<TodoPage/>}></Route>
<Route
path="/user/:user"
element={<UserTodos/>}
></Route>
</Routes>
</React.Suspense>
Every route with its own suspense
<Routes>
<Route
path="/"
element={
<React.Suspense fallback={<p>Loading...</p>}>
<MainPage />
</React.Suspense>
}
></Route>
<Route
path="/todo/:todoID"
element={
<React.Suspense fallback={<p>Loading...</p>}>
<TodoPage />
</React.Suspense>
}
></Route>
<Route
path="/user/:user"
element={
<React.Suspense fallback={<p>Loading...</p>}>
<UserTodos />
</React.Suspense>
}
></Route>
</Routes>
Upvotes: 1
Views: 1558
Reputation: 316
I have never tried this myself practically. But intuitively my guess would be that:
This is also indicated by the docs:
When a component suspends, the closest parent Suspense boundary switches to showing the fallback.
So if you want to show different fallbacks for different routes, you may choose the second approach. Else if the fallbacks are the same for all routes, then the first approach would be more maintainable.
Upvotes: 0