I'm using React router to render my different pages according to a specific url. Now I wanted to use React.lazy to lazy load all my page components:
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
const Page = React.lazy(() => {
return import("./Page");
});
const App = () => {
return (
<Router>
<React.Suspense fallback={<div>Loading page...</div>}>
<Switch>
<Route exact path="/">
<h1>Home</h1>
<Link to="/page">Go to another page</Link>
</Route>
<Route path="/page" component={Page} />
</Switch>
</React.Suspense>
</Router>
);
};
export default App;
This work really good but when I go to /page
, all my Home
disappear and I only see the fallback Loading page...
component (the page disappears then another one appears quickly which is disturbing for a user).
That's the default behaviour of React.Suspense
but is there a way in this case to keep the actual Home page rendered on the screen with the Loading page...
message at the top, and when the Page
component is loaded, just render it and replace the Home page?
This is currently only possible in the experimental Concurrent Mode. You will have to wait until this becomes generally available before using this in a production site.