electric icon indicating copy to clipboard operation
electric copied to clipboard

Add SSR Support for React Hooks

Open KyleAMathews opened this issue 1 year ago • 5 comments

This PR adds server-side rendering (SSR) support to the React hooks.

Fix https://github.com/electric-sql/electric/issues/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

KyleAMathews avatar Jan 17 '25 13:01 KyleAMathews

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)

samwillis avatar Jan 17 '25 22:01 samwillis

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.

KyleAMathews avatar Jan 17 '25 23:01 KyleAMathews

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

MarioSimou avatar Jan 22 '25 10:01 MarioSimou

@KyleAMathews Any update on this? Would be great to get this merged in with all the changes the client has undergone

ebramanti avatar Apr 05 '25 23:04 ebramanti

Not yet, we've been focused on getting electric cloud launched. Not firm when we'll get back to this. If you'd like to PR updates for the latest client and your fixes that'd be great!

KyleAMathews avatar Apr 06 '25 03:04 KyleAMathews

This is very stale and is superseded by work in TanStack DB (as per @samwillis)

icehaunter avatar Sep 24 '25 08:09 icehaunter