DEV Community

Cover image for Learn how to use React Suspense for data fetching (part 1)
Derick Zihalirwa
Derick Zihalirwa

Posted on • Updated on

Learn how to use React Suspense for data fetching (part 1)

Introduction

When a website is opened by a user, it renders all components present in the page, that's still okay, but let's say the website get bigger and bigger with more components to render and many of them are on the same page. This will cause the website to take long to download the components on the user's browser.

React provides a method called'lazy' to deal with this scenario.

A componenent that uses the lazy method get downloaded only when it's needed and not before. But if the user has a bad connectivity the component will take longer to display, the user will only see a blank screen which is not a good user experience.

blank screen while the browser is downloading a component

To prevent this, we have to display something that let the user knows what is happening in the background.

That's where the Suspence API comes in handy. let dive right in,

What is Suspense ?

The Suspense API works in conjunction with lazy components to let your users know that some loadings are happening in the background.

You can also think about it has a way to show a "Loading state..."
message, a skeleton or a spinner wheel, while the actual component is being processed and downloaded.

UI with and without Suspense

Example

Now let's use Suspense API in our application.

Basic example
To use Suspense API, you will have to rap your lazy component inside <Suspense> which you will export from React.

import React, { lazy, Suspense } from 'react'
import Spinner from './layout/spinner';
const FiciGame = lazy(() => import('./page/FiciGame'));

const App = () => {
    return (
        // Show a spinner while the profile is loading
        <div className='mx-auto w-4/12 p-8 flex justify-center self-center shadow-xl rounded-md bg-gray-900'>
            <Suspense fallback={<Spinner />}>
                <FiciGame />
            </Suspense>
        </div>
    )
}

export default App
Enter fullscreen mode Exit fullscreen mode

πŸ“Œgithub source code

Result
This is the result after adding <Suspense> and lazy loading method in our application.

Suspense in action

Conclusion

In this article We've seen how to display a loading message instead of showing a blank screen to let the users know that there's something happening in the background.

For the first part we saw how to use Suspense with lazy loading method. In the next part we will see a more advance example, we will see how Suspense lets your components β€œwait” for a request to finish before they can render.

References

If you want to connect with me, you can find me on Twitter.

πŸ‘‹ See you Soon.

Top comments (0)