If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Suspense can be a daunting concept for a lot of React developers, but it doesn't have to be. So let's simplify it. Edit score suspense is nothing more than a react built-in component that allows you to show a pending state while some child component is taking a while to render. As an example, consider a simple server component that cannot render because it is waiting on some API request to complete. So instead of leaving the user hanging with the blank screen, we can wrap our component with React suspense. This allows us to provide a fallback UI so that the user is notified that something is happening,
00:33
and once the render is complete, suspense will automatically swap out the fallback UI with the final component. With the theory out of the way, let's take a look at some practical code. Within a simple page, we wish to compute the prime factors of a given input. For this purpose, we will build a component called prime factors. That takes the input and then computes the prime factors. The heavy lifting of the component is actually going to be done by a third party, API. Within the component, we simply accept the input, pass it to this third party, API await the result of the computation, and then render out a simple ui.
01:07
Now this API will take a while to compute the result, which means that while we are waiting for the result, we cannot render the final ui and this will lead to a bad user experience. If you visit the website, we are left hanging and we see no user interface till that computation is complete. It would be great if while the computation is taking place, we can see the header of what we are trying to do along with a status indicator. I indicat that that computation is taking place. First, we create a loading placeholder for the prime factors component. This will be a dump component
01:38
that simply shows a box pulsating in place with the message computing prime factors. While that computation is taking place within our homepage, we bring in the suspense component from the React module. Suspense allows us to easily replace a component that is taking too long to render with a placeholder using the fallback prop. With this change in place, even while prime factors is still busy rendering, the server can immediately return the H one along with the prime factor loading ui. Let's verify this. By executing the code again within the browser, you can see
02:09
that the heading is already displayed along with the placeholder. While that component is still busy rendering on the server, and eventually when it comes back with a response, suspense seamlessly replaces the placeholder with the final ui.