Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the current page rendered until the new page is loaded with React.lazy and React.Suspense

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?

Edit happy-cohen-z60b9

like image 286
johannchopin Avatar asked Oct 15 '20 09:10

johannchopin


People also ask

What is lazy loading and suspense in React?

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.

How do you refresh a page without reloading in React?

Method 1: Refresh a Page Using JavaScriptwindow. location. reload(false); This method takes an optional parameter which by default is set to false.

What is the use of suspense in React?

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.


1 Answers

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.

like image 114
Mordechai Avatar answered Oct 20 '22 03:10

Mordechai