Skip to content
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

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open

Add SSR Support for React Hooks #2232

wants to merge 9 commits into from

Conversation

KyleAMathews
Copy link
Contributor

@KyleAMathews KyleAMathews commented Jan 17, 2025

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

// Remix loader
export const loader: LoaderFunction = async () => {
  return await preloadShape(itemShape())
}

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:

  1. The script tag content is parsed and stored in memory
  2. When useShape is called:
    • Checks for matching SSR data
    • If found, initializes the shape with that data before starting the stream
function getShape(stream: ShapeStream, optionsHash: string) {
  const ssrData = getSSRState().shapes[optionsHash]
  if (ssrData) {
    // Initialize with SSR data before starting stream
    shape.initializeWithSSRData(new Map(ssrData.rows))
  }
  return shape
}

Key Implementation Details

Metadata Preservation

Beyond just the data, we preserve:

  • offset: So client knows where to resume streaming
  • handle: For authentication with the streaming endpoint
  • lastSyncedAt: For cache freshness tracking

@samwillis
Copy link
Contributor

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)

@KyleAMathews
Copy link
Contributor Author

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.

@MarioSimou
Copy link

Feel free to check this draft - I did some changes on the ElectricProvider and added support for RSC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add SSR support
3 participants