React
How to use a document in a React application, and the hooks the client provides.
@voidhash/mimic has no React-specific document hook. Its React support
comes through zustand: a store mirrors the document, and components select
from the store. This page shows how the pieces fit in a React application
and lists the hooks.
The pieces
| Import | Provides |
|---|---|
@voidhash/mimic/sync | createSyncClientDocument (no React) |
@voidhash/mimic/zustand | mimic middleware, useDraft |
@voidhash/mimic/zustand-commander | useCommander, useUndoRedo, useUndoRedoKeyboard |
react (18 or 19) and zustand (5) are peer dependencies of
@voidhash/mimic.
Opening a document in a component tree
Create the document and its store once per document id, keep the store in state, and provide it through context:
import { createContext, useContext, useEffect, useState } from "react";
import { create, useStore, type StoreApi, type UseBoundStore } from "zustand";
import { createSyncClientDocument } from "@voidhash/mimic/sync";
import { mimic, type MimicSlice } from "@voidhash/mimic/zustand";
import { BOARDS, BoardDocument, DATABASE } from "./shared";
type BoardState = MimicSlice<typeof BoardDocument>;
type BoardStore = UseBoundStore<StoreApi<BoardState>>;
const BoardStoreContext = createContext<BoardStore | null>(null);
export function useBoardStore<T>(selector: (state: BoardState) => T): T {
const store = useContext(BoardStoreContext);
if (!store) throw new Error("useBoardStore must be used within BoardProvider");
return useStore(store, selector);
}
export function BoardProvider({
documentId,
children,
}: {
documentId: string;
children: React.ReactNode;
}) {
const [store, setStore] = useState<BoardStore | null>(null);
useEffect(() => {
const document = createSyncClientDocument({
primitive: BoardDocument,
url: "wss://db.example.com/v1/sessions",
database: DATABASE,
collection: BOARDS,
document: documentId,
credential: () => fetchDocumentToken(documentId),
});
const created: BoardStore = create(mimic(document, () => ({})));
setStore(() => created);
return () => {
created.getState().mimic.dispose();
document.dispose();
setStore(null);
};
}, [documentId]);
if (!store) return <p>Connecting…</p>;
return <BoardStoreContext.Provider value={store}>{children}</BoardStoreContext.Provider>;
}fetchDocumentToken is your own function that asks your backend for a
document token. Note setStore(() => created): a zustand store is itself a
function, so pass it to setState wrapped in a function.
Rendering
Components select what they need:
function Columns() {
const columns = useBoardStore((state) => state.mimic.snapshot?.[0]?.children ?? EMPTY);
return (
<ul>
{columns.map((column) => (
<li key={column.id}>{column.data.name}</li>
))}
</ul>
);
}
const EMPTY: readonly never[] = [];Use node and item ids as React keys. They are stable across edits, moves and reconnects.
Snapshots are immutable and keep the identity of unchanged parts, so
React.memo components and reference-comparing selectors skip work for
subtrees that did not change. Presence updates do not replace the snapshot.
Status
function Status() {
const isReady = useBoardStore((state) => state.mimic.isReady);
const isConnected = useBoardStore((state) => state.mimic.isConnected);
const isSaving = useBoardStore((state) => state.mimic.hasPendingChanges);
if (!isReady) return <span>Loading</span>;
if (!isConnected) return <span>Offline</span>;
return <span>{isSaving ? "Saving" : "Saved"}</span>;
}Hooks
| Hook | From | Purpose |
|---|---|---|
useDraft(store) | @voidhash/mimic/zustand | Owns a draft for a gesture; discards it on unmount |
useCommander(store) | @voidhash/mimic/zustand-commander | Returns the dispatch function for commands |
useUndoRedo(store) | @voidhash/mimic/zustand-commander | Undo and redo state and actions |
useUndoRedoKeyboard(store, options?) | @voidhash/mimic/zustand-commander | Binds the undo and redo keyboard shortcuts |
The three command-layer hooks and useDraft need a store created with
commander.middleware; see
Commands with undo.
Without zustand
The client document is framework-free. To use it with React directly,
subscribe with useSyncExternalStore; getSnapshot() returns the same
reference until the value changes, which is what that hook requires.
import { useSyncExternalStore } from "react";
import type { SyncClientDocument } from "@voidhash/mimic/sync";
function useDocumentSnapshot(document: SyncClientDocument<typeof BoardDocument>) {
return useSyncExternalStore(
(onChange) => document.subscribe({ onStateChange: onChange, onReady: onChange }),
() => document.getSnapshot(),
);
}Server rendering
A client document opens its session with the global WebSocket when it
connects, and cannot where there is none. Create
documents in an effect or an event handler, not while rendering on the
server.