Skip to main content
Complete Steps 1-2 on the Core setup page before continuing. Those steps install dependencies and initialize Velt.

Setup

Step 1: Create a CRDT text store

Use the useStore hook to create a CRDT store backed by a Yjs Y.Text. The hook handles store initialization, React lifecycle, and real-time subscriptions automatically — no manual useState/useEffect needed for store setup.
import { useStore } from '@veltdev/crdt-react';

function Component() {
  const {
    value: text,
    update: updateText,
    store,
    isLoading,
    isSynced,
    status,
    error,
  } = useStore<string>({
    storeId: 'my-text-store',
    type: 'text',
    initialValue: 'Hello, start typing here...',
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <textarea
      value={text ?? ''}
      onChange={(e) => updateText(e.target.value)}
    />
  );
}

Step 2: Read and update the store

The hook’s value field reactively tracks the current text — no manual subscription needed. Use update() to replace the entire text value. The CRDT library handles conflict-free merging with other users’ edits automatically.
// The current text is always available via the hook's `value` field
const { value: text, update: updateText } = useStore<string>({
  storeId: 'my-text-store',
  type: 'text',
  initialValue: '',
});

// Replace the entire text content
function handleChange(newText: string) {
  updateText(newText);
}

Step 3: Subscribe to real-time changes (Other Frameworks)

Use store.subscribe() to listen for changes from all collaborators. The callback fires on every change (local and remote) with the full merged text.
// Subscribe to all future changes (local and remote)
const unsubscribe = store.subscribe((newText) => {
  // Re-render the UI with the latest merged state
  renderText(typeof newText === 'string' ? newText : '');
});

// Call unsubscribe to stop listening when no longer needed
unsubscribe();
In React, the value from useStore is already reactive — no manual subscription is needed.

Step 4: Save and restore versions (optional)

Create checkpoints and roll back when needed.
The useStore hook exposes version management methods directly:
import { Version } from '@veltdev/crdt-react';

const {
  value: text,
  update: updateText,
  saveVersion,
  getVersions,
  getVersionById,
  restoreVersion,
  setStateFromVersion,
} = useStore<string>({
  storeId: 'my-text-store',
  type: 'text',
  initialValue: '',
});

// Save a named snapshot of the current state
await saveVersion('Draft v1');

// Retrieve the list of all saved versions
const versions: Version[] = await getVersions();

// Restore the store to a previously saved version
await restoreVersion(versionId);
const version = await getVersionById(versionId);
if (version) {
  await setStateFromVersion(version);
}

Step 5: Initial content with forceResetInitialContent (optional)

By default, initialValue is only applied when the document has no existing remote state. Set forceResetInitialContent to true to always reset the store to initialValue on initialization, overwriting any existing remote data.
const { value: text, update: updateText } = useStore<string>({
  storeId: 'my-text-store',
  type: 'text',
  initialValue: defaultText,
  forceResetInitialContent: true,
});

Complete Example

A complete collaborative notepad built with useStore:
Complete Implementation
import React, { useState, useEffect, useCallback } from 'react';
import { useStore, Version } from '@veltdev/crdt-react';

export const Notepad = () => {
  const [versionName, setVersionName] = useState('');
  const [versions, setVersions] = useState<Version[]>([]);

  // Use the useStore hook — handles initialization and subscriptions automatically
  const {
    value: text,
    update: updateText,
    store,
    saveVersion: storeSaveVersion,
    getVersions: storeGetVersions,
    restoreVersion: storeRestoreVersion,
    getVersionById,
    setStateFromVersion,
  } = useStore<string>({
    storeId: 'my-notepad-store',
    type: 'text',
    initialValue: 'Welcome to the Collaborative Notepad! Start typing here...',
  });

  // Fetch saved versions when store is ready
  const refreshVersions = useCallback(async () => {
    const v = await storeGetVersions();
    setVersions(v);
  }, [storeGetVersions]);

  useEffect(() => {
    if (store) refreshVersions();
  }, [refreshVersions, store]);

  // Handle text changes from the textarea
  const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    updateText(e.target.value);
  };

  // Handle saving a new version
  const handleSaveVersion = async (e: React.FormEvent) => {
    e.preventDefault();
    if (versionName.trim()) {
      await storeSaveVersion(versionName.trim());
      setVersionName('');
      await refreshVersions();
    }
  };

  // Handle restoring a version
  const handleRestoreVersion = async (versionId: string) => {
    await storeRestoreVersion(versionId);
    const version = await getVersionById(versionId);
    if (version) {
      await setStateFromVersion(version);
    }
    await refreshVersions();
  };

  return (
    <div>
      <textarea
        value={text ?? ''}
        onChange={handleTextChange}
        placeholder="Start typing..."
      />
      <div>{(text ?? '').length} character{(text ?? '').length !== 1 ? 's' : ''}</div>

      <h3>Versions</h3>
      <form onSubmit={handleSaveVersion}>
        <input
          type="text"
          value={versionName}
          onChange={(e) => setVersionName(e.target.value)}
          placeholder="Version name..."
        />
        <button type="submit">Save Version</button>
      </form>

      <ul>
        {versions.map((version) => (
          <li key={version.versionId}>
            <span>{version.versionName}</span>
            <button onClick={() => handleRestoreVersion(version.versionId)}>Restore</button>
          </li>
        ))}
      </ul>
    </div>
  );
};