I'm using React router to render my different pages according to a specific url. No 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?
It has been available for quite some time. In essence, lazy loading means that a component or a part of code must get loaded when it is required. It is also referred to as code splitting and data fetching . Talking about React specifically, it bundles the complete code and deploys all of it at the same time.
Method 1: Refresh a Page Using JavaScriptwindow. location. reload(false); This method takes an optional parameter which by default is set to false.
Suspense is not a data fetching library. It's a mechanism for data fetching libraries to communicate to React that the data a component is reading is not ready yet. React can then wait for it to be ready and update the UI.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With