top of page
Logo der Online Agentur mdwp

Suspense for Data Fetching

Suspense for Data Fetching is a new feature in React that aims to help with handling asynchronous data fetching in the user interface of an application. This feature is a clever way to optimize web applications by enabling components to suspend rendering while they are waiting for some data to arrive from a network request, causing them to 'wait' or 'suspend' until the fetching is completed.

In simple terms, React will be able to pause any state update (rendering) while components are waiting for data fetching and continue once the data is ready, hence the term ' Suspense'.

Before Suspense, React was unable to handle fetching data efficiently and needed extra libraries like Redux or Mobx to synchronize it.

Here's an example how you could utilize the Suspense for Data Fetching:

import React, { Suspense } from "react";
import { fetchData } from "./api";

const MyComponent = () => {
const data = fetchData(); // It could be an API call
return <div>{data}</div>;

export const App = () => (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />

In this example, `<Suspense>` wraps the `MyComponent` component. If `MyComponent` or any other components inside `Suspense` throw a promise (which is the case while we are waiting for data from `fetchData()`), it will catch that and show fall back UI until the promise is resolved and React can render the data loaded.

Please note that Suspense for Data Fetching is only available in experimental builds of React. The stable React release does not currently (as of November 2021) support Suspense for Data Fetching.

bottom of page