I understand that Suspense components are the React-ian approach to code splitting, which makes webpages load faster. Now, say you have a component hierarchy like this:
<App>
<Suspense fallback={<FirstLoader/>}>
<OuterWrapper>
<Suspense fallback={<SecondLoader/>}>
<InnerWrapper>
{content}
</InnerWrapper>
</Suspense>
</OuterWrapper>
</Suspense>
</App>
Assume first that only InnerWrapper
is lazy-loaded, and in the second case they are both lazy loaded.
Does React defer the loading of InnerWrapper
after OuterWrapper
is loaded, or are they both loaded simultaneously? Specifically, whether the rendering of the 2nd Suspense's fallback is deferred after the first component is loaded.
What Is Suspense, Exactly? Suspense lets your components “wait” for something before they can render. In this example, two components wait for an asynchronous API call to fetch some data: const resource = fetchProfileData(); function ProfilePage() { return ( <Suspense fallback={<h1>Loading profile...</
React Suspense is a React component that suspends a component('s) being render until a certain condition has been met, and will display a fallback option. This fallback option is required, and it may be a string or another React component such as a spinner.
Before we go on in the article, note that React Suspense is an experimental feature and is still undergoing changes, especially with the upcoming release of React 18.
In React, we can nest components inside within one another. This helps in creating more complex User Interfaces. The components that are nested inside parent components are called child components.
Does React defer the loading of InnerWrapper after OuterWrapper is loaded, or are they both loaded simultaneously? Specifically, whether the rendering of the 2nd Suspense's fallback is deferred after the first component is loaded.
Rendering of the second Suspense
will be delayed until OuterWrapper
. Everything you pass to OuterWrapper
as children:
<Suspense fallback={<SecondLoader/>}>
<InnerWrapper>
{content}
</InnerWrapper>
</Suspense>
Is passed to OuterWrapper
as props.children
when it is going to be rendered. So, rendering of second Suspense
can only happen when OuterWrapper
is fetched and executed.
Also, in the case when InnerWrapper
is lazy-loaded, it going to be fetched after OuterWrapper
is rendered. So, in this case, both components aren't fetched in parallel but one after another.
I've created an example to show it here: https://glitch.com/edit/#!/dusty-ghoul
you can play with delay after which scripts are going to be send to the client by modifying delay
parameter here:
// public/index.js
const OuterWrapper = React.lazy(() => import("./OuterWrapper.js?delay=5000"));
const InnerWrapper = React.lazy(() => import("./InnerWrapper.js?delay=1000"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With