Data Fetching with React Suspense

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