React Suspense In One Image

September 1, 2021 By Nicolas Even

The React team has published several in-depth posts about React Suspense such as this one. It took me a lot of effort to grok from them what are Suspense’s benefits and how to use it.

Now that I understand Suspense, here’s the image I wished I had seen when learning about it. I hope it’ll be useful to you:

Comparison of a component without and with React Suspense

So: a lot less boilerplate and the loading indicator clearly separated from the component.

FAQ

Why isn’t fetchData awaited in the After example?

As you can see in the After code, fetchData needs to be asynchronous (so it can call fetch to get the data via HTTP for example), however, it is not awaited, nor returns a promise, and the code still works. How come?

Suspense expects components to respect this contract :

Therefore, fetchData either throws a promise or returns the data, it never returns a promise and doesn’t need to be awaited.

For more details, you can check out this blog post, that explains algebraic effects and how they’re used in React (the “throw a pending promise” thing is a simulation of algebraic effects).

That’s the most complicated part of Suspense, which is intended to be implemented by library authors1. However, there are a few straightforward ways to implement it, such as implementing it in a caching layer.

All this to remove some boilerplate? I can do this with a HOC.

No, Suspense does much more:

Great, can I use it?

Both Suspense and Concurrent Mode are experimental features, but they’re used in production at Facebook. The development experience and results are great, so I encourage you to use them.


  1. It’s already implemented by Relay for example ↩︎