'How to fix slow page changing speed to heavy routes with React Router?
I have a React project and use React Router DOM v6 to manage all my routes.
I have a route that uses a fairly heavy component and, when switching to that heavy component, there is a 1+ second delay until the current page disappears and the new one shows up, since it's taking time to render that component.
Is there a way to change pages before trying to load the component and, perhaps, show a "loading" page while it's doing that?
EDIT: It was a little ambiguous, but by "heavy route" I meant that it renders slowly whenever you change routes to it.
Solution 1:[1]
What you can do is implement React.lazy() to lazy load the page and then use React.Suspense() to show a loading page while transitioning. Here is an example:
import React, { Suspense } from 'react';
// import MyPage from './pages/MyPage'
// instead of importing MyPage like above, use lazy, like below
const MyPage = React.lazy(() => import('./pages/MyPage'));
function App() {
return (
<Suspense
fallback={<div><p>Loading...</p></div>}
>
<Routes>
<Route path='/mypath' element={<MyPage} />
// other route data
</Routes>
</Suspense>
)
}
export default App;
This is a very simple example. What this does is when you initially load your page, MyPage will not be loaded. Loading of the page will be deferred until it is needed. Once you go to /mypath, MyPage will then be loaded and the Suspense component will show the loading <p> tag. Of course this can be any element you want or even a component.
Alternatively, what you could do is, inside your big component, you could use useState() to create a simple boolean isLoading and setIsLoading state and set it to true initially. Then, render a loading component if isLoading is true. After your operation is completed, set isLoading to false.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
