Y-Sweet React Hooks
The Y-Sweet React hooks provide a way to synchronize and update document data within React components. These hooks typically return Y.js shared types, which are similar to standard JavaScript types but offer automatic network synchronization and persistence. Specifically, the useMap
, useArray
, and useText
hooks return Yjs Shared Types (Y.Map, Y.Array, and Y.Text respectively) and automatically subscribe to their changes, triggering re-renders when updates occur.
useMap
returns aY.Map
object, which maps strings to arbitrary values, similar to a JavaScript object orMap
.useArray
returns aY.Array
object, which is similar to a JavaScript array.useText
returns aY.Text
object, which is similar to a JavaScript string.usePresence
returns a JavaScriptMap
of client IDs -> presence state (i.e.Record<string, any>
)usePresenceSetter
returns a function that can be used to set the client’s own presence state (i.e.Record<string, any>
)
In order to use Y-Sweet hooks in a component, it must be a descendant of a <YDocProvider>
component.
In the color grid example, we use a map to store the color of each cell in a grid. Similar to a JavaScript Map
(but different than a JS object), we use .get()
and .set()
to read and write values.
Refer to the api reference for more details on how to use the hooks.