@reaxis/async
v0.0.1-b
Published
Async helpers for Preact server-side-rendering with Suspense and out-of-order streaming
Downloads
6
Readme
@reaxis/async
Helper components and hooks for Preact server-side-rendering with Suspense boundaries and out-of-order streaming.
More information on out-of-order streaming rendering can be found in the React docs for their version of renderToPipeableStream
, and an explanation with some visualizations on the React 18 SSR Architecture page (Section 'React 18: Streaming HTML and Selective Hydration').
Example
import { renderToPipeableStream } from "preact-render-to-string/stream-node";
import { useAsync, AsyncBoundary } from "@reaxis/async";
function AsyncComponent() {
const result = useAsync(async () => {
await new Promise((r) => setTimeout(r, 1000));
return "rendering waited for this";
});
return <p>{result}</p>;
}
const page = (
<div>
<AsyncBoundary fallback={<i>Loading...</i>}>
<AsyncComponent />
</AsyncBoundary>
<p>Visible immediately</p>
</div>
);
const stream = renderToPipeableStream(page, {
onShellReady() {
stream.pipe(process.stdout); // pipe to webserver response
},
});
This will result in a streaming HTML response that first renders like
<div>
<i>Loading...</i>
<p>Visible immediately</p>
</div>
then after the Promise inside the useAsync
hook resolves, the <i>
element is replaced with the result from <AsyncComponent />
:
<div>
<p>rendering waited for this</p>
<p>Visible immediately</p>
</div>
All transferred through a single HTTP response, with a minimal piece of JS injected that keeps track of which elements are placeholders, and replaces those with other elements as soon as they enter the page.
More code examples can be found in the test files for now.
License, donations
AGPL-3.0. If you want to support my work, you can:
Changelog
0.0.1 (January 19, 2025)
- Initial release