How do Preact Async Server Components work? #2164
-
First of all I want to congratulate with the authors of this framework as it's really inspiring! I was interested in implementing async components in my Preact app both for easy server side data fetching and also to be able to stream the html to the client. I was wondering if you have a package separated for this that I could use, or if you could briefly explain the architecture to me so I could try to do something easier but similar. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The trick we use to make async routes work is that they are not actual Preact components. Support for async components in This has the downside that hooks or other Preact features don't work inside async routes, but given that most folks rather use them to query data from an API or a database, they tend to not need Preact features there. You might be interested in this PR to Long story short: Fresh doesn't support async server components, it supports async functions that happen to return JSX. |
Beta Was this translation helpful? Give feedback.
-
Sounds like a reasonable clever way to circumvent the problem, the downside would be to wait for the async function to return its value before start sending it to the client so no streaming for sure. But other than that
I think that the fact that you can't access hooks on the async function is not a big deal, I mean isn't it like this also in React server components? I'm not sure about it but I doubt that it could work otherwise, (maybe disable hooks on ssr async functions like it's done on normal functions? not sure how that's done since conditional run of hooks is usually not allowed) One thing that I'm stil not sure I got: will this limitation apply to all subcomponents of a route? meaning that if you find an island you stop rendering it and instead you render it only in the browser? Because in the docs I saw it's mentioned that it is only needed if any browser-only api is used making me guess that islands are rendered both on the server and the client by default. How is that done? Thanks for the explanation so far! |
Beta Was this translation helpful? Give feedback.
The trick we use to make async routes work is that they are not actual Preact components. Support for async components in
preact-render-to-string
is still pending. Instead, async routes in Fresh are essentially functions that happen to return JSX nodes. So we call all async functions before rendering, collect the return value and then do a synchronous render withpreact-render-to-string
.This has the downside that hooks or other Preact features don't work inside async routes, but given that most folks rather use them to query data from an API or a database, they tend to not need Preact features there.
You might be interested in this PR to
preact-render-to-string
which is an attempt at asy…