DEV Community

Cover image for React: Slow Suspense

Posted on • Updated on

React: Slow Suspense

There are several ways to deal with loading states, and in fact the React team came up with a solution called Suspense.

When you use Suspense directly, the fallback will show even if the fetching process is quick. And it will also disappear as soon as the fetching process is done. This would make up for a jarring UI, we can do better.

At the time of writing, there's a great package, developed by the Zeit team, called swr, which supports suspenseful data fetching.

This gist, shows a fairly simple pattern, SlowSuspense.

SlowSuspense renders its children with a Suspense boundary, when the Suspense Boundary uses the suspense-fallback, a first timer is started, if timeout occurs, then the slow-fallback is rendered.

Once the suspense settles, the suspense-fallback is unmounted, and a second timer is started, when timeout occurs, the slow-fallback is unmounted.

Should the suspense settle quickly, then we clear out all timers and prevent the slow-fallback from being rendered at all.

This CodeSandBox, has a beefed up demonstration.

Keeping track of a promise, and manage a piece of state, depending on whether or not the promise has settled, can make up for a very complicated implementation. On top of that, having to account for quick loading, or delays on the activation of the loading state, can quickly become unmanageable.

In this example, Suspense helps us remove the promise management completely, and we re-purpose the fallback props, to help us provide friendlier user experience.

Happy hacking!

Top comments (1)

sanderdebr profile image

Very helpful, thanks!