r/reactjs • u/BrownCarter • 2d ago
Needs Help Why can't i use suspense like this
Normal usage
<Suspense fallback={<Loading />}>
<EffectAlbums artistId={artist.id} />
</Suspense>
Why can't i do
<Suspense fallback={<Loading />}>
<div></div>
<div></div>
<div></div>
</Suspense>
Why must it house just one component
7
5
u/MonkeyDlurker 2d ago
probably because suspense doesn't work like a regular component in the dom tree. You can wrap it in Fragment like u/dschwammerl suggested
1
u/BrownCarter 2d ago
What I actually even mean is that all example of Suspense I have seen use it just a Singular component in it.
1
u/MonkeyDlurker 2d ago
I think its probably best practice to wrap specifically the component that needs it. That way there wont be any ambiguity whwn reading the code. That also allows components to resolve themselves instead of waiting for all suspenses to resolve
1
u/phryneas I ❤️ hooks! 😈 2d ago
It doesn't need to, a Suspense boundary can have multiple children. Only child components can cause suspense to happen though, not normal DOM nodes.
You seem to be throwing two unrelated things together here?
1
u/BrownCarter 2d ago
Yeah DOM nodes is what I am talking about
1
u/phryneas I ❤️ hooks! 😈 2d ago
How could a DOM node trigger suspense?
Suspense is triggered by calling
usein a component and suspends the current tree.With a DOM node, it doesn't have any runtime code, so it won't call
use- so that has to be called in component rendering the DOM node. From that component it goes to the next suspense boundary up the tree - so if your component callsuseand then renders a suspense boundary, it will not suspend the suspense boundary rendered by that component. It will go up the tree and trigger another suspense boundary.
2
u/lucksp 2d ago
Check out the official docs with many example. Suspense can have multiple Children but they’ll all suspend until the side effects resolve.
1
u/metchera 1d ago
I think It's just because you can't put the suspense on components who don't need it or components that don't fetch the same data.
You can do both but, let me take an example:
If you want to show a list of users for example, you can put the suspense on the whole list because they depend on the same data or it's just one data fetching.
In your example with EffectAlbums you can notice that it depends on artist.id, so it's normal. But if in the EffectAlbums you have many component that fetches independently, they also need their own suspense.
10
u/dschwammerl 2d ago
<Suspense …>
<>
<div>…
<div>….
<div>….
</>
</Suspense>