Understanding React “Suspense”

Why do we need this?

  • with this approach we need to either implement the loading screen in the component which requests / consumes the data, or expose its API to parent
  • things get more complicated the more content we need to load (what if you wanted to load a movie details page only when the reviews and all images are also already loaded?)
  • once we start making use of AsyncMode things will get even more complex — parts of your application might have new data, parts of it old, which would lead to “tearing” or “flickering” of content

Live demo


Please note that the current API is not final and will more than likely change before public release.

Let’s step through the code

Resource fetcher / cache provider / “abstractor of the API”:

A simple cache provider
  1. create a shared cache object
  2. create a “resource fetcher” (createResource) which you call with a set of parameters
  3. return a promise that will resolve after a set time, with the input value

Wait — what?

Simple AsyncText component that resolves to text prop after set time
Alternative to the simple-cache-provider mechanism. Courtesy of Alex Krolick

Using the component

Error caused by using an async component.
A Loader custom component making use of Timeout — the new primitive
  • ms prop, which indicates the time after which we want to see the fallback content (here passed to the Loader component as prop!)
  • children which should be a “function as a child” or “render prop” function; this function will be called with one parameter, which indicates if the specified time elapsed

Using the components

Using our Loader and AsyncText components together

What to expect?

Screenshot of Andre’s tweet
  • data fetching, without locking the UI and at the same time allowing users to change their decision while data is being fetched (which could result in race conditions)
  • providing good experience to users with low-end, high-latency devices
  • creating a common abstraction over “loading” state

Please note that the current API is not final and will more than likely change before public release.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Angular Directives- An Introduction

PhillyScript: Writing my own programming language

Creating GraphQL API with Koa and TypeORM

Useful tools

Advance JavaScript Concept

React Router v5

Javacript var,let & const

Proxy Objects In JavaScript, JavaScript ES6 .

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bartosz Szczeciński

Bartosz Szczeciński

More from Medium

React JS / Components , props and state

React.js useCallback Hell!

React Hooks

Curious Case of React: How to Rerender when Using Refs