What is Suspense in React? 🧐

Shubham Khandal
3 min readSep 24, 2022

Suspense for Data Fetching 🙄

Suspense GIF | GIFER

Hello Guys, Today, we will talk about Suspense in React.
In this article, we’ll know what is Suspense and how to use it.
This article is very important for React developers. So if all of you are interested then we are going on the Advance React phase. Then, Let’s Start.

Let’s start

React 16.6 added a <Suspense> component that lets you “wait” for some code to load and declaratively specify a loading state (like a spinner) while we’re waiting: 🧘🏻

Suspense for Data Fetching is a new feature that lets you also use <Suspense> to declaratively “wait” for anything else, including data.

This article focuses on the data fetching use case, but it can also wait for images, scripts, or other asynchronous work.

🔊 What Is Suspense?

Your components can “wait” for something while using suspense before rendering.

Two components in this example are awaiting an asynchronous API call to fetch some data:

How to use Suspense?

Let’s look at the simplest use case of Suspense, which is handling a pending network request in a component:

Without Suspense -

how most people — including me — handle waiting for network calls, this should sound familiar. The Spinner, Todos, and fetchdata function implementations are not important in this context.

The request’s status is monitored by the variable isLoading. If this is the case, we render a spinner to let the user know about this state. There’s nothing wrong with doing it this way at all, but let’s try handling it with suspense instead:

React had no knowledge of the network call so we had to manage the loading state using the isLoading variable. With this example, React knows that a network call is happening, and by wrapping the Todos component in Suspense, it delays rendering it until the network call is done.

Another important thing to note is the fallback property passed to Suspense. This is whatever we want to render while waiting for the network call to finish. It could be a spinner, skeleton loader, or just plain nothing.

React will render whatever the value of fallback is while waiting for the network request to finish.

In the next article, we will see Data fetching approaches which is the next phase of Suspense.

Guys, Now I know Suspense in React

Thanks 🙏 for reading !!
Please 🤝 follow me for more stories !!

--

--

Shubham Khandal

👋 Hi, I’m shubham khandal 👀 I’m interested in React & JavaScript. 🌱 I’m always in learning mode. 💞️ I collaborate on React & JavaScript Projects..