Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get loading progress in React.lazy and Suspense

I'm using lazy to split my routes and I wanna know if there is any way I can get the loading progress in lazy and suspense.

Currently I'm using it like this.

const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));

function App() {
  return (
    <Router>
      <Switch>
        <Suspense fallback={<div>loading</div>}>
          <Route path="/" exact={true} component={Home} />
          <Route path="/About" component={About} />
        </Suspense>
      </Switch>
    </Router>
  );
}

■ But I want to show the loading progress (like youtube).
■ Is there any way I can retrieve the progress for example like below.

<Suspense fallback={({progress}) => <LoadingBar progress={progress}/>}>
like image 776
Thu San Avatar asked Jan 24 '19 02:01

Thu San


People also ask

Does React lazy increase performance?

lazy() and React. Suspense . Lazy loading is a great way to boost page performance while keeping users on your site. If used appropriately, it may help you build efficient and user-friendly solutions.

What is lazy () in React?

React. lazy() is a function that enables you to render a dynamic import as a regular component. Dynamic imports are a way of code-splitting, which is central to lazy loading. A core feature as of React 16.6, React. lazy() eliminates the need to use a third-party library such as react-loadable .

What is lazy and suspense in React?

The React. lazy function allows you to dynamically import a dependency and render that dependency as a component in a single line of code. The Lazy component should then be rendered inside Suspense Component which helps to reflect some fallback content meanwhile the lazy component loads.


2 Answers

This is my solution:

const LazyLoad = () => {
    useEffect(() => {
        NProgress.start();

        return () => {
            NProgress.stop();
        };
    });

    return '';
};

<Suspense fallback={<LazyLoad />}>
like image 135
Tung Luong Thanh Avatar answered Oct 17 '22 20:10

Tung Luong Thanh


lazy uses JavaScript promises which either resolve or reject, but they don't report any progress.

You can however fake the progress with something like http://ricostacruz.com/nprogress/ which increments the progress bar randomly.

like image 36
amann Avatar answered Oct 17 '22 19:10

amann