Before starting with Suspense we need to talk about React.lazy API and the concept of lazy loading in programming.
Lazy loading refers to the possibility of loading elements into memory ONLY when we really need them.
Example: If we have a slider that holds 40 images but only shows 1 on the screen, we will generate an expensive loading time before showing that single image. The correct way of doing would be to only load the image that will be presented to the user, meaning the usage of the Lazy Loading concept !
In web programming another amazing way of using it would be by loading only those components that are needed by the user at a particular time. For example, if we have an application that needs authentication it would be amazing to just load the Login component and leave the rest of the app out of the browser memory, this way not only we speed up loading processes but we also increase the security of the application as we don’t let unauthorized users access private code.
So now that we understand lazy loading, let’s start…
It’s an amazing feature introduced with React 16, and originally, it was meant to be used with React.lazy API to split the code, rendering a holder element until the lazy component finished loading. The main disadvantage was that it didn’t let the developers work with it if we were using a server-side rendering engine (SSR).
With React 18 this changes, as now it’s compatible with SSR, but there’s one more problem, Suspense was meant to be much more than just a way of splitting code as the inclusion of pre fetching data functionality is in React developer’s intentions but it’s still in beta.
Suspense it’s an engine API that intercepts a component’s promise and stops it’s execution until it’s complete, in the meantime, it can use something else in it’s place to fill the hole.
If you have used Suspense, you may know of it’s fallback attribute, that receives a component to be loaded until the previously talked promise finishes.
<Suspense fallback={<Loader />}>
With React 18 and it’s Concurrent Suspense (the latest version of the engine), it completely removes the elements from the DOM, different to the previous version where they were only hidden. This increases the possibilities and stability of the app as the lifecycles events are not fired only when really needed.
To manage multiple Suspense instances, we can now use Suspense List ! it’s a really cool wrapper that helps the dev, decide on how to reveal the suspended elements to the user.
The main magic comes from this two properties:
revealOrder:
which defines the order in which the elements are introduced to the user and it can be in a forwards, backwards or together fashion.