How to correctly chain Suspense
Answered
D Trombett posted this in #help-forum
In a page I have the following structure (simplified):
Assuming I have a function to download data 1, data 2 and data 3, how can I use
<div>
<div>Data 1</div>
<div>Data 2</div>
</div>
<div>
<div>Data 1</div>
<div>Data 3 (requires data 2)</div>
</div>Assuming I have a function to download data 1, data 2 and data 3, how can I use
Suspense to correctly stream the components as soon as the data is available without fetching the same data (being fetch or a db) more times?Answered by B33fb0n3
yes, you would fetch it multiple times. When using the react cache the result from the first request to your DB will be memorized and cached for the request. So you can call your fetch function 100.000 times in all components everywhere and you still would have only 1 request to your db
11 Replies
@D Trombett In a page I have the following structure (simplified):
tsx
<div>
<div>Data 1</div>
<div>Data 2</div>
</div>
<div>
<div>Data 1</div>
<div>Data 3 (requires data 2)</div>
</div>
Assuming I have a function to download data 1, data 2 and data 3, how can I use `Suspense` to correctly stream the components as soon as the data is available without fetching the same data (being `fetch` or a db) more times?
first you need to seperate each div with data to a different component. Then you can wrap each component in either his own suspense or create one suspense boundary. Like that you can stream the data easily
Ok ok, but considering that every div is a different component, I would need to load the data in every component
Aaand... How can I avoid downloading the data multiple times (like from a DB)?
Maybe using React's
cache?@D Trombett Maybe using React's `cache`?
yes, you would fetch it multiple times. When using the react cache the result from the first request to your DB will be memorized and cached for the request. So you can call your fetch function 100.000 times in all components everywhere and you still would have only 1 request to your db
Answer
Ok, thanks a lot, I'll try!
@D Trombett Ok, thanks a lot, I'll try!
When will you try?
Uh, I think tomorrow?
So, I've just tried and it seems to work as expected! Thank you so much
happy to help