Skip to main content

Command Palette

Search for a command to run...

Data Fetching with React Suspense

Published
2 min read

Overview

Suspense lets components "wait" for something before they can render. It suspends(you could guess that from the name) component rendering if data needs to be pulled from external resources, external API, or the backend. It is a declarative way of fetching data as it abstracts all the processes involved in data fetching. It is not a substitute for fetch.

A key thing to note is that Suspense is not a data-fetching library. Suspense serves as a mechanism for data fetching libraries to communicate to React that the data a component is reading is not ready yet.

The Suspense component was created to make integrating data fetching libraries with React Components feel natural. At the moment, not many libraries are integrated with Suspense, this explains why it is not mainstream yet. One of the libraries with Suspense support is the new Relay API.

Suspense

<Suspense fallback={<FallbackComponent />}>
  <Component />
</Suspense>

Props

Suspense has two props. The "children" prop and the "fallback" prop:

  • children: This is the actual user interface (UI) we want to render. If "children" suspends while rendering, the Suspense boundary will render "fallback" instead.

  • fallback: This is the alternative UI that will be rendered if the actual UI has not finished loading. It accepts any ReactNode, usually, a loading spinner or skeleton should suffice. Suspense will automatically switch from "fallback" to "children" once the data is ready.

Example

Data fetching with Suspense differs from the usual data fetching. I have created an example repo just for this purpose. Check here.

Resources

B
Blossom3y ago

This is simple to digest and gives a quick intro to what suspense in react is

1
A

I'm happy you found it easy to understand. Clear communication is something I strive for and I'm glad to know I did that well in this case. Thank you for your feedback. it means a lot.