Introduction

Use these guides to add Yjs-based CRDT to your project with Velt. Pick the React Hook wrapper for the fastest integration in React apps, or the core library for other frameworks and custom implementations.

Setup

Step 1: Install Dependencies

npm:
npm install @veltdev/crdt-react @veltdev/crdt @veltdev/react
yarn:
yarn add @veltdev/crdt-react @veltdev/crdt @veltdev/react

Step 2: Initialize Velt in your app

Initialize the Velt client by following the Velt Setup Docs. This is required for the collaboration engine to work.

Step 3: Initialize a CRDT store

import { useVeltCrdtStore } from '@veltdev/crdt-react';

function Component() {
  const { store } = useVeltCrdtStore<string>({
    id: 'my-collab-note',
    type: 'text',
    initialValue: 'Hello, world!',
  });
  return null;
}

Step 4: Set or update the store value

Set or update local changes to the store.
import { useVeltCrdtStore } from '@veltdev/crdt-react';

function Component() {
  const { update } = useVeltCrdtStore<string>({ id: 'my-collab-note', type: 'text' });
  const onChange = (e) => update(e.target.value);
  return <input onChange={onChange} />;
}

Step 5: Listen for changes

Listen and subscribe for updates from local and remote peers.
import { useEffect } from 'react';
import { useVeltCrdtStore } from '@veltdev/crdt-react';

function Component() {
  const { store } = useVeltCrdtStore<string>({ id: 'my-collab-note', type: 'text' });

  useEffect(() => {
    if (!store) return;
    const unsubscribe = store.subscribe((newValue) => {
      console.log('Updated value:', newValue);
    });
    return unsubscribe;
  }, [store]);

  return null;
}

Step 6: Save and restore versions

Create checkpoints and roll back when needed.
import { useVeltCrdtStore } from '@veltdev/crdt-react';

function Component() {
  const { saveVersion, getVersions, getVersionById, setStateFromVersion } =
    useVeltCrdtStore<string>({ id: 'my-collab-note', type: 'text' });

  async function onSave() {
    const versionId = await saveVersion('Checkpoint');
    console.log('Saved version:', versionId);
  }

  async function onRestoreLatest() {
    const versions = await getVersions();
    if (versions.length === 0) return;
    const latest = versions[0];
    await setStateFromVersion(latest);
  }

  return (
    <div>
      <button onClick={onSave}>Save Version</button>
      <button onClick={onRestoreLatest}>Restore Latest</button>
    </div>
  );
}

APIs

Custom Encryption

Encrypt CRDT data before it’s stored in Velt by registering a custom encryption provider. For CRDT methods, input data is of type Uint8Array | number[].
async function encryptData(config: EncryptConfig<number[]>): Promise<string> {
  const encryptedData = await yourEncryptDataMethod(config.data);
  return encryptedData;
}

async function decryptData(config: DecryptConfig<string>): Promise<number[]> {
  const decryptedData = await yourDecryptDataMethod(config.data);
  return decryptedData;
}

const encryptionProvider: VeltEncryptionProvider<number[], string> = {
  encrypt: encryptData,
  decrypt: decryptData,
};

<VeltProvider
  apiKey="YOUR_API_KEY"
  encryptionProvider={encryptionProvider}
/>

See also: setEncryptionProvider() · VeltEncryptionProvider · EncryptConfig · DecryptConfig

Initialization

useVeltCrdtStore

React hook to create and sync a collaborative CRDT store.
const {
  value,
  versions,
  store,
  update,
  saveVersion,
  getVersions,
  getVersionById,
  restoreVersion,
  setStateFromVersion,
} = useVeltCrdtStore<string>({
  id: 'my-collab-note',
  type: 'text',
  initialValue: 'Hello, world!',
  debounceMs: 100,
});

Common Methods

These methods are available in both React and non-React frameworks.

update

Update the store value and sync to peers.
  • Params: newValue: T
  • Returns: void
update('New value');

saveVersion

Save a snapshot of the current state as a named version.
  • Params: versionName: string
  • Returns: Promise<string>
await saveVersion('Checkpoint');

getVersions

Fetch all saved versions.
  • Returns: Promise<Version[]>
const versions = await getVersions();

getVersionById

Fetch a specific version by ID.
  • Params: versionId: string
  • Returns: Promise<Version | null>
const version = await getVersionById('abc123');

setStateFromVersion

Restore the store state from a specific version object.
  • Params: version: Version
  • Returns: Promise<void>
await setStateFromVersion(version);

React-Specific Methods

value

Current value of the store (React hook only).
  • Type: T | null
console.log(value);

versions

List of all stored versions (React hook only).
  • Type: Version[]
console.log(versions);

store

Underlying Velt Store instance (React hook only).
  • Type: Store<T> | null
console.log(store);

restoreVersion()

Restore the store to a specific version by ID (React hook only).
  • Params: versionId: string
  • Returns: Promise<boolean>
await restoreVersion('abc123');

Non-React Specific Methods

getValue

Get the current store value (non-React frameworks only).
  • Returns: T
const value = store.getValue();

subscribe

Subscribe to changes in the store (non-React frameworks only).
  • Params: (newValue: T) => void
  • Returns: () => void (unsubscribe)
const unsubscribe = store.subscribe(console.log);

destroy

Destroy the store, cleaning up resources and listeners (non-React frameworks only).
  • Returns: void
store.destroy();

Yjs Integration Methods

getDoc

Get the underlying Yjs document.
  • Returns: Y.Doc
const ydoc = store.getDoc();

getProvider

Get the provider instance for the store.
  • Returns: Provider
const provider = store.getProvider();

getText

Get the Y.Text instance if store type is ‘text’.
  • Returns: Y.Text | null
const ytext = store.getText();

getXml

Get the Y.XmlFragment instance if store type is ‘xml’.
  • Returns: Y.XmlFragment | null
const yxml = store.getXml();