React Lazy & Suspense

React Lazy

  • In the large-scale project, there is lots of component, the size of chunk file will be large which increase the loading time and affect the user experience

  • By using react lazy, it divides a chunk file into several chunk files. Only when the component is used, the corresponding chunk file will be loaded, which will decrease the loading time as the size of chunk is decreased

  • The common use case is to put react lazy outside the router

import React,{ lazy, Suspense} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import reportWebVitals from './reportWebVitals';

const App = lazy(() => import('./App'));
const Test = lazy(() => import('./test'));

ReactDOM.render(
  <Router>
    <Suspense fallback={<div>Loading....</div>}>
    <Switch>
        <Route path = "/test" component = {Test}/>
        <Route path = "/" component = {App}/>
    </Switch>
    </Suspense>
  </Router>,
  document.getElementById('root')
);
Before using react lazy 1
Before using react lazy 2
After using react lazy 1
After using react lazy 2
  • From the above examples, we can see that a chunk file is divided into 2 files, the file only appear when the corresponding page is loaded

React Suspense

Only Suspense-enabled data sources will activate the Suspense component. They include:

  • Data fetching with Suspense-enabled frameworks like Relay and Next.js

  • Lazy-loading component code with lazy

  • Reading the value of a Promise with use

<Suspense fallback={<Loading />}>
  <Albums />
</Suspense>

Last updated

Was this helpful?