umma.dev

Suspense and Lazy Loading in React

Integrating Suspense and Lazy Loading into a React app can make the app a lot more efficent.

Suspense

Suspense in React delays the rendering of a component if the component has been imported from outside of the current component.

It handles the loading state whilst the app is trying to import a component but does not deal with errors.

const Example = React.Lazy(() => import('./Example))

<Suspense fallback={<p>Loading</p>}>
    <Example />
</Suspense>

Usually loading states are dealt with using componentDidMount() or via Redux; when the component renders it notices there isnโ€™t any data and whilst the app waits it renders a loading icon like a spinner and then the component is rendered again, this isnโ€™t very efficent.

Lazy Loading

The idea of lazy loading is enable less JavaScript to be loaded when the user is viewing a website or app, and hence this improve the performance of a website.
const Example = React.lazy(() => import('./Example))

. . .

<Router>
    <Suspense fallback={"Loading"}>
        <Switch>
            <Route path='/' component={Example} />
        </Switch>
    </Suspense>
</Router>