1

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>
1
  • I'd like to know this too myself Commented Dec 11, 2022 at 12:37

1 Answer 1

0

I have never tried this myself practically. But intuitively my guess would be that:

  • If you wrap everything in one root Suspense, that single fallback will be shown for every suspended route.
  • But if you wrap every route in its own suspense block, the corresponding fallback will be shown for each route.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.