Magic of React Suspense with concurrent react and React.lazy API


React.Suspense in simple words means we can suspend the rendering of our component or components until some condition is met( for example data from an endpoint or a resource is loaded) and until then show a fallback(for-example a spinner)

Why do we need this?

If suspense is all about just showing a spinner till data loads, can we not do that today as well?

I mean we have been doing the same thing since a long time by keeping a loading state as true and till the data is not fetched we show a spinner and when data fetch is complete we set the loading state to false.

An example of how we have been currently doing it:

state = {
loading: true,
data: null

So the question is if it can be done even today then what is it that suspense is bringing into our codebase?

The answer to that is yes it’s still possible to use loading state and play around with it to show/hide the spinner but as the application grows complex this becomes tedious to manage.

For example:-


In the above example we can have 4 api calls:
1) component making one api call for getting basic information about a Restaurant

2) api to fetch all the images of that Restaurant
3) api to fetch all reviews
4) api to fetch some details around those individual reviews like comments, likes etc.

The problem with the above code structure is that we need to somehow manage the loading state and data fetching states for all those api calls that are happening above.

So what is the solution?

For the above problem we have multiple solutions which can be as follows:

  • Delegate all api calling logic into the parent container and let all of them wait until all data fetching is complete and pass data to child components as props. The problem with this approach is now the parent needs to be aware of all api calls which are needed by child components and also maintain a complex state for all these api responses.
  • Make all the child components smart/stateful components and let each of them manage their own loading and data states. This is complex since converting a stateless component to a stateful component is not something we would want to do.
  • The third solution is using Suspense

With Suspense it works differently. How?

With suspense and react-cache, we can use our same functional component and still fetch data from it.

The difference here being instead of fetching data from a lifecycle method like componentDidMount we will fetch this data from inside of render .

How is this even possible?

This becomes possible using react-cache and suspense

Now a word of caution, react-cache is still unstable and it’s implementation or api might change over time.

An example of how to use react-cache to create a restaurant list fetching resource:-

read original article here