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.

NameTypeDefaultDescription
autoConnectbooleantrueWhether the middleware connects the document when the store is created.
autoSubscribebooleantrueWhether the middleware mirrors document and presence changes into the store.

The mimic slice

NameTypeDescription
documentClientDocumentThe client document, for writing.
snapshotInferSnapshot | undefinedThe document as the user sees it: the optimistic value with the newest open draft's edits on top.
presence{ selfId, self, others, all } | undefinedThe participants' presence; undefined when the document has no presence.
isConnectedbooleanA session is open.
isReadybooleanThe document's state has arrived.
isReadOnlybooleanWrites would throw ReadOnlyError.
syncErrorMimicClientError | undefinedSet while local edits are not reaching the server.
connectionErrorError | undefinedThe last failed autoConnect attempt; cleared once a session opens.
pendingCountnumberUnanswered local edits.
hasPendingChangesbooleanWhether any edit is unanswered.
activeDraftIdsreadonly string[]The open drafts.
dispose() => voidStops 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.snapshot keeps 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()}
    />
  );
}
MemberPurpose
draftThe 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
dispatchDispatches 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