-
Notifications
You must be signed in to change notification settings - Fork 183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add SSR Support for React Hooks #2232
base: main
Are you sure you want to change the base?
Conversation
I like this strategy a lot, it's almost identical to what I experimented with when chatting to Valter a few months ago: https://github.com/samwillis/ssr-shape-poc/blob/main/src/app/shapes.tsx (tiny POC with no actual shapes) |
I want to make another go sometime at looking at RSC — it is fairly different and worth a serious think through as it might change a bit how everything is ordered. |
Feel free to check this draft - I did some changes on the |
This PR adds server-side rendering (SSR) support to the React hooks.
Fix #2219
With this PR, non-RSC SSR Just Works™️ by adding a new
<ElectricScripts />
component to your layout.Supporting RSC proved more complicated than I wanted to handle with this PR — https://github.com/electric-sql/electric/tree/rsc is where I got to with it. I liked the hydration pattern in tanstack/react-query (https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr) and that's what I was trying to implement but got bogged down in build errors, etc. so decided to focus on getting this in first as it works great in Remix & with Next pre-app-router. The tricky part about RSC is you don't have any global context anymore as each component renders by itself. So hydration into useShape on the server & client is different. Anyways, something to dig into another time.
Here's a detailed breakdown of the implementation:
Core SSR Flow
1. Preloading Data on Server
2. Server Rendering
The server component renders as normal with
useShape
using the preloaded data.3. Serialization to HTML
The SSR state is serialized into the HTML using a script tag with a new
<ElectricScripts />
component.Similar to frameworks like React Query and SWR, we fetch data during the server render phase. However, unique to Electric, we also need to preserve metadata like the shape's offset and handle for proper client-side rehydration.
4. Client Hydration
On the client, before any components render:
useShape
is called:Key Implementation Details
Metadata Preservation
Beyond just the data, we preserve: