React Suspense: Async Rendering in React - 401-advanced-javascript-bp/seattle-javascript-401d30 GitHub Wiki

React Suspense: Async Rendering in React

Excerpt

What is React Suspense? Suspense is a new React feature that was announced recently at the JSConf Conference in Iceland. It aims to help with handling async operations respectively in regard to CPU power and data fetching.

Suspense allows you to defer rendering part of your application tree until some condition is met (for example, data from an endpoint or a resource is loaded).

In this article, we’ll explore Suspense and see what potential impact this feature will have on the way React apps are built.

Why React Suspense? There’s a good chance you’ve come across SPAs that make use of a loading icon as an indicator that data is being fetched. This is a common method used to ensure good UX for apps that are fetching data from external sources. All you have to do is check if the data has been successfully fetched, and if not, show a spinner.

However, this might not scale when the data fetching process becomes complicated:

When both the parent and child component have loading states When you need a component to load only after some other (child) components have been loaded The key module that makes Suspense work is the createFetcher function. Available on npm as the simple-cache-provider, it works as outlined below:

In the render() method, read a value from the cache If the value is already cached, the render continues like normal If the value is not already cached, the cache throws an error When the promise resolves, React continues from where it stopped import { createResource } from 'simple-cache-provider';

const someFetcher = createResource(async () => {
const res = await fetch(https://api.github.com/search/users?q=yomete); return await res.json(); });

export default someFetcher; We create a fetcher function using createResource from the simple-cache-provider package.

Note: The simple-cache-provider is still an experimental feature, not to be used in a production app.

When initiating createResource, a function is passed which is expected to return a Promise. If the Promise resolves, React carries on and render the results, else, an error is thrown.

The function can then be used in a render function to display the results.

Additional Resources

Dan Abramov - Suspense!

Async Redux Actions with Redux Thunk

Async Actions