Zustand bindings
Mirroring a client document into a zustand store with the mimic middleware, and staging gestures with useDraft.
@voidhash/mimic/zustand connects a client document to a
zustand store. The store gets a mimic slice
that always reflects the document, next to whatever local state you keep.
This is the recommended way to render a document with React. This page covers
the middleware and the useDraft hook.
The middleware
mimic(document, config, options?) is a zustand middleware. config is your
own state creator; the middleware adds the mimic slice to its result.
import { create } from "zustand";
import { createSyncClientDocument } from "@voidhash/mimic/sync";
import { mimic } from "@voidhash/mimic/zustand";
const document = createSyncClientDocument({
primitive: BoardDocument,
url,
database: databaseId,
collection: collectionId,
document: documentId,
credential,
});
export const useBoardStore = create(
mimic(document, () => ({
selectedCardId: null as string | null,
})),
);By default the middleware subscribes to the document and calls
document.connect() when the store is created. A failed connection attempt
is stored in mimic.connectionError instead of being thrown.
| Name | Type | Default | Description |
|---|---|---|---|
autoConnect | boolean | true | Whether the middleware connects the document when the store is created. |
autoSubscribe | boolean | true | Whether the middleware mirrors document and presence changes into the store. |
The mimic slice
| Name | Type | Description |
|---|---|---|
document | ClientDocument | The client document, for writing. |
snapshot | InferSnapshot | undefined | The document as the user sees it: the optimistic value with the newest open draft's edits on top. |
presence | { selfId, self, others, all } | undefined | The participants' presence; undefined when the document has no presence. |
isConnected | boolean | A session is open. |
isReady | boolean | The document's state has arrived. |
isReadOnly | boolean | Writes would throw ReadOnlyError. |
syncError | MimicClientError | undefined | Set while local edits are not reaching the server. |
connectionError | Error | undefined | The last failed autoConnect attempt; cleared once a session opens. |
pendingCount | number | Unanswered local edits. |
hasPendingChanges | boolean | Whether any edit is unanswered. |
activeDraftIds | readonly string[] | The open drafts. |
dispose | () => void | Stops mirroring the document into the store. |
Reading in components
Select from the slice like any zustand state:
function BoardTitle() {
const name = useBoardStore((state) => state.mimic.snapshot?.[0]?.data.name);
const isReady = useBoardStore((state) => state.mimic.isReady);
if (!isReady) return <p>Loading…</p>;
return <h1>{name}</h1>;
}The slice is built so that selectors re-render only when they should:
mimic.snapshotkeeps its reference until the document's value changes. Connection changes and presence changes do not replace it.- Presence changes replace only
mimic.presence. A component that selects from the snapshot does not re-render when a cursor moves.
Writing
Write through the document on the slice:
function AddColumn() {
const document = useBoardStore((state) => state.mimic.document);
return (
<button
onClick={() =>
document.transaction((root) => {
root.children.first()?.children.insertLast({ type: "column", name: "New" });
})
}
>
Add column
</button>
);
}The store updates synchronously, so the component re-renders with the new value before the server has confirmed it. For writes with undo and redo, see Commands with undo.
A store per document
A store wraps one document. When the document is chosen at runtime, create the store when you open the document and provide it through React context:
const store = create(mimic(document, () => ({ selectedCardId: null as string | null })));
<BoardStoreContext.Provider value={store}>
<Board />
</BoardStoreContext.Provider>;Call store.getState().mimic.dispose() and document.dispose() when the
document is closed.
Drafts in components
useDraft(store) owns one draft for a gesture. It
needs a store that also has the command layer's slice; see
Commands with undo for
commander.middleware.
import { useDraft } from "@voidhash/mimic/zustand";
function DraggableCard({ cardId }: { cardId: string }) {
const store = useContext(BoardStoreContext)!;
const { draft, begin, commit, discard } = useDraft(store);
return (
<Card
onDragStart={() => begin()}
onDrag={(x, y) =>
draft?.update((root) => {
root.findByIdAcrossTree(cardId)?.update({ x, y });
})
}
onDragEnd={() => commit()}
onDragCancel={() => discard()}
/>
);
}| Member | Purpose |
|---|---|
draft | The open draft, or null |
begin() | Opens a draft. Throws InvalidStateError when one is already open |
commit() | Submits the draft as one transaction. Throws when the staged edits no longer apply; the draft then stays open |
discard() | Drops the draft |
dispatch | Dispatches commands into the draft while it is open, otherwise to the document |
While the draft is open, mimic.snapshot shows its staged edits, so every
component renders the preview. The draft is discarded when the component
unmounts. Only one draft can be active in a store at a time.
Next
- Commands with undo
- React: the hooks at a glance.