Shared Types
Understanding Yjs shared types: Y.Map, Y.Array, Y.Text, and Y.XmlFragment.
Overview
Yjs provides four primary shared types. Each has specific characteristics for different use cases.
Y.Map
A key-value store similar to JavaScript’s Map. Supports nested shared types for hierarchical structures.
Key behavior: Setting a plain object snapshots it—later mutations don’t sync. For granular updates, nest Y.Map instances.
Best For:
- Keyed data where order doesn’t matter
- Configuration objects
- Entity storage (keyed by ID)
- Hierarchical structures (nested maps)
Y.Array
An ordered list similar to JavaScript’s Array. Handles concurrent insertions gracefully with position-aware merging.
Key behavior: Reordering items (delete + insert) creates copies, not moves. For reorderable collections, store only IDs in the array.
Best For:
- Ordered lists where sequence matters
- ID arrays for ordering (with content in a separate Y.Map)
- Text editor paragraphs
- Timeline events
Avoid Complex Objects in Arrays
Don’t store complex objects in Y.Array if you need to reorder them. Store IDs in the array and content in a Y.Map instead. See ID-Based Storage.
Y.Text
A shared string optimized for collaborative text editing. Supports character-level insertions, deletions, and formatting attributes.
Key behavior: Concurrent edits merge at character positions. Formatting uses Quill-style delta operations.
// Rich text formatting
yText.insert(0, 'Bold text', { bold: true })
yText.format(0, 4, { italic: true }) // Apply to range
Editor Bindings: Integrates with Quill, ProseMirror, Monaco, CodeMirror, and TipTap through official bindings.
Best For:
- Rich text documents
- Code editors
- Chat messages
- Any content needing character-level merging
Y.XmlFragment
An XML-like structure for representing DOM or document trees. Used primarily with ProseMirror for complex rich text with nested elements.
Best For:
- ProseMirror integration
- DOM-like document structures
- Complex rich text with nested elements
Type Selection Guide
| Data Type | Use Case | Conflict Resolution |
|---|---|---|
| Y.Map | Key-value data, entities | Last-writer-wins per key |
| Y.Array | Ordered lists, sequences | Position-aware insertion |
| Y.Text | Text content, rich text | Character-level merging |
| Y.XmlFragment | DOM structures | Element-level operations |
See Also
- Document Structure - Organizing shared types in a Y.Doc
- Text Editors - Y.Text in practice