# 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

```jsx
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](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-MOVLivSbcnLGjmOv_kS%2F-MOVW1sziwIdlAJHszhm%2Fimage.png?alt=media\&token=6364ea5e-0fed-4127-976c-bbc51366b555)

![Before using react lazy 2](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-MOVLivSbcnLGjmOv_kS%2F-MOVWD85w3CMJR3zNUac%2Fimage.png?alt=media\&token=e5599e93-df4c-49bf-86d5-f7ac74ccc4d0)

![After using react lazy 1](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-MOVLivSbcnLGjmOv_kS%2F-MOVWd7Q8DXgyflPfLIy%2Fimage.png?alt=media\&token=d6490fb9-4fb1-4444-b6bc-e0583924b1e7)

![After using react lazy 2](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-MOVLivSbcnLGjmOv_kS%2F-MOVX7Rch-dX_2UDHDfR%2Fimage.png?alt=media\&token=44f3ca4b-b7c1-4e94-93cd-011dc3cb00ee)

* 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](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/getting-started/react-essentials)
* Lazy-loading component code with [`lazy`](https://react.dev/reference/react/lazy)
* Reading the value of a Promise with [`use`](https://react.dev/reference/react/use)

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