Introduction

Traditionally, dealing with asynchronous code in React has required some boilerplate:

  • Make a wrapper component to show a pending or rejected state.
  • Make our components keeping track of _pending _and _rejected _state and inform the wrapper component about state changes.

But ideally, we want:

  • To care only about the fulfilled state in our components.
  • To abstract away the _pending _and _rejected _state.

Here, I am going to show you how to achieve just that and how to structure asynchronous code in a modern way.

Tools

We are going to use the Suspense component and Error Boundaries. They have been available since React 16.6.

Suspense

The Suspense component will display a fallback user interface until all of its children will have their state fulfilled:

<Suspense fallback="Waiting...">
  <ChildComponent1 />
  <ChildComponent2 />
</Suspense>

#react #promises #error-boundaries #asynchronous #suspense

Managing asynchronous code in React
1.15 GEEK