@MaximeHeckel

Asynchronous rendering with React

November 6, 2018 / 6 min read

Last Updated: November 6, 2018

Since I’ve started playing with React a couple of years ago, I’ve always been a big fan of functional components. Their simplicity and conciseness make them easy to read and test. The problem though was that, until now, there was no way to do asynchronous calls which is the crucial part of most applications in the real world, so classes were always the way to go.
However, starting from React 16.6.0 and the new Suspense API, this is not an issue anymore, functional components can now perform asynchronous calls and render data that comes from them. In this post, I’m going to show you an up to date example so you can easily test the Suspense API.

Note: Although it’s available through the last official version of React, using Suspense as I’ll show you in this post is not yet intended for production. This example solely exists as an experiment.

What is Suspense in a nutshell?

Suspense basically suspends the rendering of a component while loading data from a cache. This means that our component will only show up once the whole tree is ready. If the data we’re trying to render is not in the cache, the cache throws a Promise. When the promise resolves, the rendering continues. 
While all of this is happening, Suspense will render a fallback component which could be for example a loading indicator, a message, or anything we usually render in our applications to signal the user that something asynchronous is happening.

A new way to build components

As of today, when we want to render a component that shows some data coming from an asynchronous call in React, we’re stuck with classes. We have to use the component lifecycle methods to ensure the call happens on mount, and use the local state to manage the loading state. We can see below a small example of a pattern that I’m sure pretty much every React developer had to follow:

React component doing an asynchronous call before rendering the data implemented using a Class

1
import React, { Component, Fragment } from 'react';
2
3
class ClassicAsync extends Component {
4
constructor(props) {
5
super(props);
6
this.state = { loading: false, title: null };
7
}
8
9
componentDidMount() {
10
fetch('https://jsonplaceholder.typicode.com/todos/')
11
.then((response) => response.json())
12
.then((json) => this.setState({ loading: false, data: json }));
13
}
14
15
renderList = (data) => {
16
return (
17
<ul>
18
{data.map((item) => (
19
<li style={{ listStyle: 'none' }} key={item.id}>
20
{item.title}
21
</li>
22
))}
23
</ul>
24
);
25
};
26
27
render() {
28
const { loading, data } = this.state;
29
30
return (
31
<Fragment>
32
<h2 style={{ textAlign: 'center' }}>
33
{`React: ${React.version} Demo`}
34
</h2>
35
{loading ? 'Classic loading placeholder' : this.renderList(data)}
36
</Fragment>
37
);
38
}
39
}
40
41
export default ClassicAsync;

How Suspense changes that? Well, quite a lot actually if you compare the code above with the following one:

React component doing an asynchronous call before rendering the data implemented using React Suspense.

1
import React, { Suspense, Fragment } from 'react';
2
3
// Fetcher code goes here
4
const getDate = () => Fetcher.read();
5
6
const List = () => {
7
const data = getData();
8
return (
9
<ul>
10
{data.map((item) => (
11
<li style={{ listStyle: 'none' }} key={item.id}>
12
{item.title}
13
</li>
14
))}
15
</ul>
16
);
17
};
18
19
const App = () => (
20
<Fragment>
21
<h2>{`React: ${React.version} Demo`}</h2>
22
<Suspense fallback={<div>Loading...</div>}>
23
<List />
24
</Suspense>
25
</Fragment>
26
);

As we can see with this example: no more class! Suspense is managing for us the loading state through the fallback prop, which is rendered until List is ready to be rendered, that is when the dependent asynchronous call resolves and returns the data. However, this is only a partial example. As stated in the first part, the rendering of List in this example is suspended while loading data from a cache, which is what the Fetcher function is all about.

Using react-cache

This is key for getting the example above to work. The caching part is needed for Suspense to read the data from the asynchronous call.
Before diving in the details, let’s look at how the Fetcher function is implemented for our example:

Fetcher resource implementation using functions from react-cache

1
import { unstable_createResource } from 'react-cache';
2
3
const Fetcher = unstable_createResource(() =>
4
fetcher('https://jsonplaceholder.typicode.com/todos').then((r) => r.json())
5
);

For this post I used react-cache. It’s a package made by the React core team that provides a basic cache that is going to store asynchronous data, like the data that we’re getting once our fetch call resolves, and allows us to access that data asynchronously. In the code snippet above we basically use the unstable_createResource function where we pass our asynchronous call, which will initiate a cache and store the resulting data into it. Accessing that data from the cache is done through the read function as we can see in the Code Snippet 2. However, this way of doing caching is currently not meant to be used in production (the React team emphasized this quite a bit in the README of this repository).

Full Example

Here’s the full example for this article:

The full example of a functional React component using the Suspense API

1
import React, { Suspense, Fragment } from 'react';
2
import { unstable_createResource } from 'react-cache';
3
4
const Fetcher = unstable_createResource(() =>
5
fetcher('https://jsonplaceholder.typicode.com/todos').then((r) => r.json())
6
);
7
8
const getDate = () => Fetcher.read();
9
10
const List = () => {
11
const data = getData();
12
return (
13
<ul>
14
{data.map((item) => (
15
<li style={{ listStyle: 'none' }} key={item.id}>
16
{item.title}
17
</li>
18
))}
19
</ul>
20
);
21
};
22
23
const App = () => (
24
<Fragment>
25
<h2>{`React: ${React.version} Demo`}</h2>
26
<Suspense fallback={<div>Loading...</div>}>
27
<List />
28
</Suspense>
29
</Fragment>
30
);

I made this example available in a Github repository based on create-react-app so you can also give it a try and experiment with Suspense very quickly!

I really can’t wait for this pattern to be ready for production. Combining Suspense and the recently announced React hooks is getting us closer to building React apps fully based on functional components. If you want to learn more about Suspense here’s a really complete summary in a tweet from a member of the React team:

What to read next?
If you want to read more about React or frontend development, you can check the following articles:

Liked this article? Share it with a friend on Twitter or support me to take on more ambitious projects to write about. Have a question, feedback or simply wish to contact me privately? Shoot me a DM and I'll do my best to get back to you.

Have a wonderful day.

– Maxime

How the new React Suspense API might reshape the way we build components