Add ConnectionManager for robust React lifecycle handling #4028
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
ConnectionManagersingleton that uses reference counting and deferred cleanup to handle React StrictMode's double-mount behaviorretain()/release()instead of direct connect/disconnectuseSyncExternalStorefor tear-free state reads in ReactChanges
src/sdk/connection_manager.ts- Core ConnectionManager implementationsrc/react/SpacetimeDBProvider.ts- Now uses ConnectionManagersrc/react/connection_state.ts- Simplified type, imports from ConnectionManagersrc/sdk/db_connection_builder.ts- AddedgetUri()andgetModuleName()methodssrc/sdk/db_connection_impl.ts- Minor type updates for ConnectionManager integrationtests/connection_manager.test.ts- 33 unit testsTest plan
pnpm testpasses (104 tests)pnpm buildpassesMotivation
The Problem
React StrictMode double-mounts components in development to help catch bugs:
Without ConnectionManager, you get either:
Why ConnectionManager? (vs alternatives)
useSyncExternalStoreConnectionManager approach (TanStack Query pattern):
setTimeout(0)lets StrictMode remount cancel cleanupWhy Two
useSyncExternalStoreUsages?The SDK now has two places using
useSyncExternalStore. They solve different problems:useTableConnectionManagerDbConnection.db.tableNamecallbacksConnectionManagersingletonisActive,identity,errorchangeuseTableassumes a connection existsConnectionManagermanages WHEN the connection existsThe Layered Architecture
useTablesyncs data from an existing connectionConnectionManagersyncs connection state AND manages when the connection exists