React hooks for real-time collaborative features using Yjs and Hocuspocus
npm install @mexty/realtimeReact hooks for real-time collaborative features using Yjs and Hocuspocus.
``bash`
npm install @mexty/realtime
`tsx
import { useCollabSpace } from "@mexty/realtime";
// 🧠 Example 1: Collaborative JSON document editor
export function DocumentEditor({ blockId }: { blockId: string }) {
const { state, update } = useCollabSpace(block:${blockId}, {
document: {
title: "Untitled",
content: "Write something...",
},
game: { weights: [] },
});
// ✅ Partial update usage
const handleTitleChange = (e: React.ChangeEvent
update({ document: { ...state.document, title: e.target.value } });
};
// ✅ Functional update usage
const resetContent = () => {
update((prev) => ({
...prev,
document: { ...prev.document, content: "" },
}));
};
return (
// 🧩 Example 2: Multiplayer tower game state
export function TowerGame({ blockId }: { blockId: string }) {
const { state, update } = useCollabSpace(block:${blockId}, {
document: {},
game: { weights: [] as { team: string; pos: number }[] },
});
// ✅ Append new weight (functional update)
const addWeight = (team: string) => {
update((prev) => ({
...prev,
game: {
...prev.game,
weights: [...prev.game.weights, { team, pos: Math.random() * 100 }],
},
}));
};
// ✅ Clear game state (partial update)
const resetGame = () => {
update({ game: { weights: [] } });
};
return (
{JSON.stringify(state.game, null, 2)}
API
$3
#### Parameters
-
documentName: string - Unique identifier for the collaborative document
- initialState: T - Initial state object for the collaborative space
- options?: CollabSpaceOptions - Optional configuration#### Returns
-
state: T - Current collaborative state
- update: (updateFn: UpdateFunction - Function to update state
- isConnected: boolean - WebSocket connection status
- connectionStatus: 'connecting' | 'connected' | 'disconnected' | 'error' - Detailed connection status
- userId: string - Anonymous user ID (persisted in localStorage)#### Options
`tsx
interface CollabSpaceOptions {
websocketUrl?: string;
onConnect?: () => void;
onDisconnect?: () => void;
onError?: (error: Error) => void;
}
``- 🔄 Real-time collaborative state synchronization
- 🆔 Anonymous user authentication with persistent IDs
- 🔗 Automatic WebSocket connection management
- 📱 React hooks for easy integration
- 🎯 TypeScript support with full type safety
- 🏗️ Built on Yjs and Hocuspocus for reliability
MIT