What Problem Is React Suspense Trying To Solve?

I've seen some examples in, but I want to know the problem that they are trying to solve and/or what's the magic behind it. And how can I use it in real projects aside from what's already in the react docs.



There are two use cases for React Suspense that I know of (and pretty sure more to be discovered). Please note, in the answer below, I am using suspense as a pragmatic reference, in reality there are more components which are used, such as lazy, react-cache etc.

#1 Make it easier to obtain lower Time To Interactive

A lower time to interactive a.k.a TTI metric is a way to measure how fast your website feels to a user. If you inspect your network resources in your browsers dev tools, you will see that a very significant time is spent in waiting to download the javascript file. Even if it is minified and compressed, it might not be optimal.

For e.x. if your website at some time requires a data visualisation library (say Highcharts), if it is not the first thing that your user would see, you don't need to send that visualization component with the first javascript file. That will save a lot of size from your initial bundle and improve your TTI metric.

This is done by combined magic of webpack dynamic imports, react Lazy and React Suspense (that is what the docs point to)

#2 Handle the usual cases around data fetching

This I think is still a work in progress, but is something I remember react team is working on. If your component needs to get its data from a server (API call), then you will see some common concerns and you will try to handle them in some capacity:

  1. Show loading indicator if request is taking long
  2. What if your request errors out (Error boundaries do that for you now)
  3. What if you would like to cache your costly network requests

These are common concerns and that is where suspense will help out.

Additional Resources which might be of interest

  1. Dan Abramovs talk at jsConf introducing suspense to the world.
  2. A nice post on medium showing the benefit of code splitting and impact on TTI