clockworklabs/SpacetimeDB · error · Error

useSpacetimeDB must be used within a SpacetimeDBProvider com

Error message

useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?

What it means

useSpacetimeDB reads the SpacetimeDBContext React context. When the context value is undefined - i.e. no SpacetimeDBProvider is mounted above the calling component - it throws immediately. Other hooks (useTable, useReducer, useProcedure) catch this error and rethrow it with their own guidance.

Source

Thrown at crates/bindings-typescript/src/react/useSpacetimeDB.ts:13

import { createContext, useContext } from 'react';
import type { ConnectionState } from './connection_state';

export const SpacetimeDBContext = createContext<ConnectionState | undefined>(
  undefined
);

// Throws an error if used outside of a SpacetimeDBProvider
// Error is caught by other hooks like useTable so they can provide better error messages
export function useSpacetimeDB(): ConnectionState {
  const context = useContext(SpacetimeDBContext) as ConnectionState | undefined;
  if (!context) {
    throw new Error(
      'useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?'
    );
  }
  return context;
}

View on GitHub (pinned to 524b4487d9)

Solutions

  1. Wrap the component tree with <SpacetimeDBProvider> at a common ancestor (typically the app root)
  2. In tests, wrap the render in the provider or mock the context before rendering hook-consuming components
  3. Check that any separately-rooted UI (overlays, portals with their own root) is also inside a provider

Example fix

// before
root.render(<Dashboard />); // Dashboard uses useTable -> throws

// after
root.render(
  <SpacetimeDBProvider>
    <Dashboard />
  </SpacetimeDBProvider>
);
Defensive patterns

Strategy: validation

Validate before calling

// Ensure the provider is an ancestor of every hook consumer before rendering:
root.render(
  <SpacetimeDBProvider>
    <App />
  </SpacetimeDBProvider>
);

Try / catch

// In an error boundary, degrade gracefully instead of crashing the tree:
static getDerivedStateFromError(e: Error) {
  return { missingProvider: e.message.includes('SpacetimeDBProvider') };
}

Prevention

When it happens

Trigger: Rendering a component that calls useSpacetimeDB (directly or via useTable/useReducer/useProcedure) outside a <SpacetimeDBProvider> subtree.

Common situations: Forgot to wrap the app in SpacetimeDBProvider; the provider is a sibling instead of an ancestor; a component rendered through a separate createRoot (dev overlay, modal micro-frontend, test render) that has no provider; unit tests rendering the component standalone.

Related errors


AI-assisted analysis of clockworklabs/SpacetimeDB@524b4487d9 (2026-08-16). Data as JSON: /api/errors/f1acfe1c72ec61ac. Report an issue: GitHub.