---
meta:
title: "@liveblocks/react"
parentTitle: "API Reference"
description: "API Reference for the @liveblocks/react package"
alwaysShowAllNavigationLevels: false
---
`@liveblocks/react` provides you with [React](https://react.dev/) bindings for
our realtime collaboration APIs, built on top of WebSockets. Read our
[getting started](/docs/get-started) guides to learn more.
## Suspense
All Liveblocks React components and hooks can be exported from two different
locations, `@liveblocks/react/suspense` and `@liveblocks/react`. This is because
Liveblocks provides two types of hooks; those that support
[React Suspense](https://react.dev/reference/react/Suspense), and those that
don’t.
```tsx
// Import the Suspense hook
import { useThreads } from "@/liveblocks/react/suspense";
// Import the regular hook
import { useThreads } from "@/liveblocks/react";
```
We recommend importing from `@liveblocks/react/suspense` and using Suspense by
default, as it often makes it easier to build your collaborative application.
If you’re using the non-standard [`createRoomContext`](#createRoomContext)
function to build your hooks, you must
[enable suspense differently](#createRoomContext-Suspense).
### Suspense hooks
Suspense hooks can be wrapped in [`ClientSideSuspense`][], which acts as a
loading spinner for any components below it. When using this, all components
below will only render once their hook contents have been loaded.
```tsx
import { ClientSideSuspense, useStorage } from "@liveblocks/react/suspense";
function App() {
Loading…}>
;
}
function Component() {
// `animals` is always defined
const animals = useStorage((root) => root.animals);
// ...
}
```
Advanced hooks using the `{ ..., error, isLoading }` syntax, such as
[`useThreads`][], can also use
[`ErrorBoundary`](https://github.com/bvaughn/react-error-boundary) to render an
error if the hook runs into a problem.
```tsx
import { ClientSideSuspense, useThreads } from "@liveblocks/react/suspense";
import { ErrorBoundary } from "react-error-boundary";
function App() {
return (
Error}>
Loading…}>
);
}
function Component() {
// `threads` is always defined
const { threads } = useThreads();
// ...
}
```
An advantage of Suspense hooks is that you can have multiple different hooks in
your tree, and you only need a single `ClientSideSuspense` component to render a
loading spinner for all of them.
### Regular hooks
Regular hooks often return `null` whilst a component is loading, and you must
check for this to render a loading spinner.
```tsx
import { useStorage } from "@liveblocks/react";
function Component() {
// `animals` is `null` when loading
const animals = useStorage((root) => root.animals);
if (!animals) {
return
Loading…
;
}
// ...
}
```
Advanced hooks using the `{ ..., error, isLoading }` syntax, such as
[`useThreads`][], require you to make sure there isn’t a problem before using
the data.
```tsx
import { useThreads } from "@liveblocks/react";
function Component() {
// Check for `error` and `isLoading` before `threads` is defined
const { threads, error, isLoading } = useThreads();
if (error) {
return
Error
;
}
if (isLoading) {
return
Loading…
;
}
// ...
}
```
### ClientSideSuspense
Liveblocks provides a component named `ClientSideSuspense` which works as a
replacement for `Suspense`. This is helpful as our Suspense hooks will throw an
error when they’re run on the server, and this component avoids this issue by
always rendering the `fallback` on the server.
```tsx
import { ClientSideSuspense } from "@liveblocks/react/suspense";
function Page() {
return (
+++
Loading…}>
+++
);
}
```
#### Loading spinners
Instead of wrapping your entire Liveblocks application inside a single
`ClientSideSuspense` component, you can use multiple of these components in
different parts of your application, and each will work as a loading fallback
for any components further down your tree.
```tsx
import { ClientSideSuspense } from "@liveblocks/react/suspense";
function Page() {
return (
My title
+++
Loading…}>
+++
);
}
```
This is a great way to build a static skeleton around your dynamic collaborative
application.
## Liveblocks
### LiveblocksProvider
Sets up a client for connecting to Liveblocks, and is the recommended way to do
this for React apps. You must define either `authEndpoint` or `publicApiKey`.
Resolver functions should be placed inside here, and a number of other options
are available, which correspond with those passed to [`createClient`][]. Unlike
[`RoomProvider`][], `LiveblocksProvider` doesn’t call Liveblocks servers when
mounted, and it should be placed higher in your app’s component tree.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
```tsx title="All LiveblocksProvider props" isCollapsable isCollapsed
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
// const response = await fetch("/api/liveblocks-auth", {
// method: "POST",
// headers: {
// Authentication: "",
// "Content-Type": "application/json",
// },
// body: JSON.stringify({ room }),
// });
// return await response.json();
// }}
//
// Alternatively, use a public key
// publicApiKey="pk_..."
//
// Throttle time (ms) between WebSocket updates
throttle={100}
// ---
// Prevent browser tab from closing while local changes aren’t synchronized yet
preventUnsavedChanges={false}
// ---
// Throw lost-connection event after 5 seconds offline
lostConnectionTimeout={5000}
// ---
// Disconnect users after X (ms) of inactivity, disabled by default
backgroundKeepAliveTimeout={undefined}
// ---
// Resolve user info for Comments, Text Editor, and Notifications
resolveUsers={async ({ userIds }) => {
const usersData = await __getUsersFromDB__(userIds);
return usersData.map((userData) => ({
name: userData.name,
avatar: userData.avatar.src,
}));
}}
// ---
// Resolve room info for Notifications
resolveRoomsInfo={async ({ roomIds }) => {
const documentsData = await __getDocumentsFromDB__(roomIds);
return documentsData.map((documentData) => ({
name: documentData.name,
// url: documentData.url,
}));
}}
// ---
// Resolve group info for Comments and Text Editor
resolveGroupsInfo={async ({ groupIds }) => {
const groupsData = await __getGroupsFromDB__(groupIds);
return groupsData.map((groupData) => ({
avatar: groupData.avatar.src,
name: groupData.name,
// description: groupData.description,
}));
}}
// ---
// Resolve mention suggestions for Comments and Text Editor
resolveMentionSuggestions={async ({ text, roomId }) => {
const workspaceUsers = await __getWorkspaceUsersFromDB__(roomId);
if (!text) {
// Show all workspace users by default
return __getUserIds__(workspaceUsers);
} else {
const matchingUsers = __findUsers__(workspaceUsers, text);
return __getUserIds__(matchingUsers);
}
}}
// ---
// Polyfill options for non-browser environments
polyfills={
{
// atob,
// fetch,
// WebSocket,
}
}
// ---
// Set the location of the "Powered by Liveblocks" badge
// "top-right", "bottom-right", "bottom-left", "top-left"
badgeLocation="bottom-right"
>
{/* children */}
);
}
```
The URL of your back end’s [authentication endpoint](/docs/authentication)
as a string, or an async callback function that returns a Liveblocks token
result. The result is cached by the Liveblocks client, and called fresh only
when necessary, so never cache it yourself. Either `authEndpoint` or
`publicApiKey` are required. Learn more about [using a URL
string](#LiveblocksProviderAuthEndpoint) and [using a
callback](#LiveblocksProviderCallback).
The public API key taken from your project’s
[dashboard](/dashboard/apikeys). Generally not recommended for production
use. Either `authEndpoint` or `publicApiKey` are required. [Learn
more](#LiveblocksProviderPublicKey).
The throttle time between WebSocket messages in milliseconds, a number
between `16` and `1000` is allowed. Using `16` means your app will update 60
times per second. [Learn more](#LiveblocksProviderThrottle).
When set, navigating away from the current page is prevented while
Liveblocks is still synchronizing local changes. [Learn
more](#prevent-users-losing-unsaved-changes).
After a user disconnects, the time in milliseconds before a
[`"lost-connection"`](/docs/api-reference/liveblocks-client#Room.subscribe.lost-connection)
event is fired. [Learn more](#LiveblocksProviderLostConnectionTimeout).
The time before an inactive WebSocket connection is disconnected. This is
disabled by default, but setting a number will activate it. [Learn
more](#LiveblocksProviderBackgroundKeepAliveTimeout).
A function that resolves user information in
[Comments](/docs/ready-made-features/comments), [Text
Editor](/docs/ready-made-features/text-editor), and
[Notifications](/docs/ready-made-features/notifications). Return an array of
`UserMeta["info"]` objects in the same order they arrived. [Learn
more](#LiveblocksProviderResolveUsers).
A function that resolves room information in
[Notifications](/docs/ready-made-features/notifications). Return an array of
`RoomInfo` objects in the same order they arrived. [Learn
more](#LiveblocksProviderResolveRoomsInfo).
A function that resolves group information in
[Comments](/docs/ready-made-features/comments) and [Text
Editor](/docs/ready-made-features/text-editor). Return an array of
`GroupInfo` objects in the same order they arrived. [Learn
more](#LiveblocksProviderResolveGroupsInfo).
A function that resolves mention suggestions in
[Comments](/docs/ready-made-features/comments) and [Text
Editor](/docs/ready-made-features/text-editor). Return an array of user IDs
or mention objects. [Learn
more](#LiveblocksProviderResolveMentionSuggestions).
Place polyfills for `atob`, `fetch`, and `WebSocket` inside here. Useful
when using a non-browser environment, such as
[Node.js](#LiveblocksProviderNode) or [React
Native](#LiveblocksProviderReactNative).
The location of the "Powered by Liveblocks" badge. Can be set to either
`"top-right"`, `"bottom-right"`, `"bottom-left"`, or `"top-left"`. [Learn
more](#Powered-by-Liveblocks-branding).
Deprecated. For new rooms, use [`engine: 2`](#RoomProvider) instead. Engine
2 rooms have native support for streaming. This flag will be removed in a
future version, but will continue to work for existing engine 1 rooms for
now. [Learn more](/docs/guides/the-new-storage-engine-and-its-benefits).
#### LiveblocksProvider with public key [#LiveblocksProviderPublicKey]
When creating a client with a public key, you don’t need to set up an
authorization endpoint. We only recommend using a public key when prototyping,
or on public landing pages, as it makes it possible for end users to access any
room’s data. You should instead use an
[auth endpoint](#LiveblocksProviderAuthEndpoint).
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
#### LiveblocksProvider with auth endpoint [#LiveblocksProviderAuthEndpoint]
If you are not using a public key, you need to set up your own `authEndpoint`.
Please refer to our [Authentication guide](/docs/authentication).
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
Never cache your authentication endpoint, as your client will not function
correctly. The Liveblocks client will cache results for you, only making
requests to the endpoint if necessary, such as when the token has expired.
#### LiveblocksProvider with auth endpoint callback [#LiveblocksProviderCallback]
If you need to add additional headers or use your own function to call your
endpoint, `authEndpoint` can be provided as a custom callback. You should return
the token created with
[`Liveblocks.prepareSession`](/docs/api-reference/liveblocks-node#access-tokens)
or [`liveblocks.identifyUser`](/docs/api-reference/liveblocks-node#id-tokens),
learn more in [authentication guide](/docs/rooms/authentication).
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
// Fetch your authentication endpoint and retrieve your access or ID token
// ...
return { token: "..." };
}}
>
{/* children */}
);
}
```
`room` is the room ID that the user is connecting to. When using
[Notifications](/docs/ready-made-features/comments/email-notifications), `room`
can be `undefined`, as the client is requesting a token that grants access to
multiple rooms, rather than a specific room.
##### Fetch your endpoint
Here’s an example of fetching your API endpoint at `/api/liveblocks-auth` within
the callback.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
const response = await fetch("/api/liveblocks-auth", {
method: "POST",
headers: {
Authentication: "",
"Content-Type": "application/json",
},
// Don't forget to pass `room` down. Note that it
// can be undefined when using Notifications.
body: JSON.stringify({ room }),
});
return await response.json();
}}
>
{/* children */}
);
}
```
##### Token details
You should return the token created with
[`Liveblocks.prepareSession`](/docs/api-reference/liveblocks-node#access-tokens)
or [`liveblocks.identifyUser`](/docs/api-reference/liveblocks-node#id-tokens).
These are the values the functions can return.
1. A valid token, it returns a `{ "token": "..." }` shaped response.
1. A token that explicitly forbids access, it returns an
`{ "error": "forbidden", "reason": "..." }` shaped response. If this is
returned, the client will disconnect and won't keep trying to authorize.
Any other error will be treated as an unexpected error, after which the client
will retry the request until it receives either 1. or 2.
#### WebSocket throttle [#LiveblocksProviderThrottle]
By default, the client throttles the WebSocket messages sent to one every 100
milliseconds, which translates to 10 updates per second. It’s possible to
override that configuration with the `throttle` option with a value between `16`
and `1000` milliseconds.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
This option is helpful for smoothing out realtime animations in your
application, as you can effectively increase the framerate without using any
interpolation. Here are some examples with their approximate frames per second
(FPS) values.
```ts
throttle: 16, // 60 FPS
throttle: 32, // 30 FPS
throttle: 200, // 5 FPS
```
#### Prevent users losing unsaved changes [#prevent-users-losing-unsaved-changes]
Liveblocks usually synchronizes milliseconds after a local change, but if a user
immediately closes their tab, or if they have a slow connection, it may take
longer for changes to synchronize. Enabling `preventUnsavedChanges` will stop
tabs with unsaved changes closing, by opening a dialog that warns users. In
usual circumstances, it will very rarely trigger.
```tsx
function Page() {
return (
...
);
}
```
More specifically, this option triggers when:
- There are unsaved changes after calling any hooks or methods, in all of our
products.
- There are unsaved changes in a
[Text Editor](/docs/ready-made-features/text-editor).
- There’s an unsubmitted comment in the
[Composer](/docs/api-reference/liveblocks-react-ui#Composer).
- The user has made changes and is currently offline.
Internally, this option uses the
[beforeunload event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
#### Lost connection timeout [#LiveblocksProviderLostConnectionTimeout]
If you’re connected to a room and briefly lose connection, Liveblocks will
reconnect automatically and quickly. However, if reconnecting takes longer than
usual, for example if your network is offline, then the room will emit an event
informing you about this.
How quickly this event is triggered can be configured with the
`lostConnectionTimeout` setting, and it takes a number in milliseconds.
`lostConnectionTimeout` can be set between `1000` and `30000` milliseconds. The
default is `5000`, or 5 seconds.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
You can listen to the event with [`useLostConnectionListener`][]. Note that this
also affects when `others` are reset to an empty array after a disconnection.
This helps prevent temporary flashes in your application as a user quickly
disconnects and reconnects. For a demonstration of this behavior, see our
[connection status example][].
#### Background keep-alive timeout [#LiveblocksProviderBackgroundKeepAliveTimeout]
By default, Liveblocks applications will maintain an active WebSocket connection
to the Liveblocks servers, even when running in a browser tab that’s in the
background. However, if you’d prefer for background tabs to disconnect after a
period of inactivity, then you can use `backgroundKeepAliveTimeout`.
When `backgroundKeepAliveTimeout` is specified, the client will automatically
disconnect applications that have been in an unfocused background tab for _at
least_ the specified time. When the browser tab is refocused, the client will
immediately reconnect to the room and synchronize the document.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
`backgroundKeepAliveTimeout` accepts a number in milliseconds—we advise using a
value of at least a few minutes, to avoid unnecessary disconnections.
#### resolveUsers [#LiveblocksProviderResolveUsers]
[Comments](/docs/ready-made-features/comments) and
[Text Editor](/docs/ready-made-features/text-editor) store user IDs in its
system, but no other user information. To display user information in Comments,
Text Editor, and Notifications components, such as a user’s name or avatar, you
need to resolve these IDs into user objects. This function receives a list of
user IDs and you should return a list of user objects of the same size, in the
same order.
User IDs are automatically resolved in batches with a maximum of 50 users per
batch to optimize performance and prevent overwhelming your user resolution
function.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
const usersData = await __getUsersFromDB__(userIds);
return usersData.map((userData) => ({
name: userData.name,
avatar: userData.avatar.src,
}));
}}
// Other props
// ...
>
{/* children */}
);
}
```
The name and avatar you return are rendered in
[`Thread`](/docs/api-reference/liveblocks-react-ui#Thread) components.
##### User objects
The user objects returned by the resolver function take the shape of
`UserMeta["info"]`, which contains `name` and `avatar` by default. These two
values are optional, though if you’re using the
[Comments default components](/docs/api-reference/liveblocks-react-ui#Components),
they are necessary. Here’s an example of `userIds` and the exact values
returned.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
// ["marc@example.com", "nimesh@example.com"];
console.log(userIds);
return [
{ name: "Marc", avatar: "https://example.com/marc.png" },
{ name: "Nimesh", avatar: "https://example.com/nimesh.png" },
];
}}
// Other props
// ...
>
{/* children */}
);
}
```
You can also return custom information, for example, a user’s `color`:
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
// ["marc@example.com"];
console.log(userIds);
return [
{
name: "Marc",
avatar: "https://example.com/marc.png",
// +++
color: "purple",
// +++
},
];
}}
// Other props
// ...
>
{/* children */}
);
}
```
##### Accessing user data
You can access any values set within `resolveUsers` with the
[`useUser`](/docs/api-reference/liveblocks-react#useUser) hook.
```tsx
import { useUser } from "@liveblocks/react/suspense";
function Component() {
const user = useUser("marc@example.com");
// { name: "Marc", avatar: "https://...", ... }
console.log(user);
}
```
#### resolveRoomsInfo [#LiveblocksProviderResolveRoomsInfo]
When using
[Notifications](/docs/ready-made-features/comments/email-notifications) with
[Comments](/docs/ready-made-features/comments), room IDs will be used to
contextualize notifications (e.g. “Chris mentioned you in _room-id_”) in the
[`InboxNotification`](/docs/api-reference/liveblocks-react-ui#InboxNotification)
component. To replace room IDs with more fitting names (e.g. document names,
“Chris mentioned you in _Document A_”), you can provide a resolver function to
the `resolveRoomsInfo` option in [`LiveblocksProvider`](#LiveblocksProvider).
This resolver function will receive a list of room IDs and should return a list
of room info objects of the same size and in the same order.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
const documentsData = await __getDocumentsFromDB__(roomIds);
return documentsData.map((documentData) => ({
name: documentData.name,
// url: documentData.url,
}));
}}
// Other props
// ...
>
{/* children */}
);
}
```
In addition to the room’s name, you can also provide a room’s URL as the `url`
property. If you do so, the
[`InboxNotification`](/docs/api-reference/liveblocks-react-ui#InboxNotification)
component will automatically use it. It’s possible to use an inbox
notification’s `roomId` property to construct a room’s URL directly in React and
set it on
[`InboxNotification`](/docs/api-reference/liveblocks-react-ui#InboxNotification)
via `href`, but the room ID might not be enough for you to construct the URL,
you might need to call your backend for example. In that case, providing it via
`resolveRoomsInfo` is the preferred way.
#### resolveGroupsInfo [#LiveblocksProviderResolveGroupsInfo]
When using group mentions with [Comments](/docs/ready-made-features/comments)
and [Text Editor](/docs/ready-made-features/text-editor), group IDs will be used
instead of user IDs. Similarly to
[`resolveUsers`](#LiveblocksProviderResolveUsers), you can provide a resolver
function to the `resolveGroupsInfo` option in
[`LiveblocksProvider`](#LiveblocksProvider) to assign information like names and
avatars to group IDs.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
const groupsData = await __getGroupsFromDB__(groupIds);
return groupsData.map((groupData) => ({
name: groupData.name,
avatar: groupData.avatar.src,
// description: groupData.description,
}));
}}
// Other props
// ...
>
{/* children */}
);
}
```
##### Accessing group info
You can access any values set within `resolveGroupsInfo` with the
[`useGroupInfo`](/docs/api-reference/liveblocks-react#useGroupInfo) hook.
```tsx
import { useGroupInfo } from "@liveblocks/react/suspense";
function Component() {
const group = useGroupInfo("group-engineering");
// { name: "Engineering", avatar: "https://...", ... }
console.log(group);
}
```
#### resolveMentionSuggestions [#LiveblocksProviderResolveMentionSuggestions]
To enable creating mentions in [Comments](/docs/ready-made-features/comments)
and [Text Editor](/docs/ready-made-features/text-editor), you can provide a
resolver function to the `resolveMentionSuggestions` option in
[`LiveblocksProvider`](#LiveblocksProvider). These mentions will be displayed in
the [`Composer`](/docs/api-reference/liveblocks-react-ui#Composer) component and
in text editors.
This resolver function will receive the mention currently being typed (e.g. when
writing “@jane”, `text` will be `jane`) and should return a list of user IDs
matching that text. This function will be called every time the text changes but
with some debouncing.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
const workspaceUsers = await __getWorkspaceUsersFromDB__(roomId);
if (!text) {
// Show all workspace users by default
return __getUserIds__(workspaceUsers);
} else {
const matchingUsers = __findUsers__(workspaceUsers, text);
return __getUserIds__(matchingUsers);
}
}}
// Other props
// ...
>
{/* children */}
);
}
```
##### Group mentions
To support group mentions in [Comments](/docs/ready-made-features/comments) and
[Text Editor](/docs/ready-made-features/text-editor), you can return a list of
mention objects instead of user IDs to suggest a mix of user and group mentions.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
function App() {
return (
{
const dbUsers = await __findUsersFromDB__(roomId);
const dbGroups = await __findGroupsFromDB__(roomId);
// Show groups and users matching the text being typed
return [
...dbGroups.map((group) => ({
kind: "group",
id: group.id,
})),
...dbUsers.map((user) => ({
kind: "user",
id: user.id,
})),
];
}}
// Other props
// ...
>
{/* children */}
);
}
```
The mention objects specify which kind of mention it is, the ID to mention (user
ID or group ID), etc.
```tsx
// A user mention suggestion
{
kind: "user",
id: "user-1",
}
// A group mention suggestion
{
kind: "group",
id: "group-1",
}
// A group mention suggestion with fixed group members
// When using fixed group members via `userIds`, they will take precedence
// if the group ID exists on Liveblocks.
{
kind: "group",
id: "here",
userIds: ["user-1", "user-2"],
}
```
#### LiveblocksProvider for Node.js [#LiveblocksProviderNode]
To use `@liveblocks/client` in Node.js, you need to provide [`WebSocket`][] and
[`fetch`][] polyfills. As polyfills, we recommend installing [`ws`][] and
[`node-fetch`][].
```bash
npm install ws node-fetch
```
Then, pass them to the `LiveblocksProvider` polyfill option as below.
```tsx
import { LiveblocksProvider } from "@liveblocks/react/suspense";
import fetch from "node-fetch";
import WebSocket from "ws";
function App() {
return (
{/* children */}
);
}
```
Note that `node-fetch` v3+
[does not support CommonJS](https://github.com/node-fetch/node-fetch/blob/main/docs/v3-UPGRADE-GUIDE.md#converted-to-es-module).
If you are using CommonJS, downgrade `node-fetch` to v2.
#### LiveblocksProvider for React Native [#LiveblocksProviderReactNative]
To use `@liveblocks/client` with [React Native](https://reactnative.dev/), you
need to add an [`atob`][] polyfill. As a polyfill, we recommend installing
[`base-64`][].
```bash
npm install base-64
```
Then you can pass the `decode` function to our `atob` polyfill option when you
create the client.
```ts
import { LiveblocksProvider } from "@liveblocks/react/suspense";
import { decode } from "base-64";
function App() {
return (
{/* children */}
);
}
```
#### Powered by Liveblocks branding
By default, Liveblocks displays a "Powered by Liveblocks" badge in your
application. You can adjust the position of the badge by setting the
`badgeLocation` property on `LiveblocksProvider`.
```tsx title="Set badge location"
// "top-right", "bottom-right", "bottom-left", "top-left"
```
If you wish to remove remove the badge entirely, you can do so by following
these steps:
1. In the Liveblocks dashboard, navigate to your
[team’s settings](/dashboard/settings).
2. Under **General**, toggle on the remove "Powered by Liveblocks" branding
option.
Removing the "Powered by Liveblocks" badge on your projects requires a
[paid plan](/pricing/). See the [pricing page](/pricing/) for more information.
### createLiveblocksContext
This used to be the default way to start your app, but now it’s recommended for
advanced usage only. We generally recommend using [`LiveblocksProvider`][] and
following [typing your data with the Liveblocks interface](#Typing-your-data),
unless you need to define multiple room types in your application.
Creates a [`LiveblocksProvider`][] and a set of typed hooks. Note that any
`LiveblocksProvider` created in this way takes no props, because it uses
settings from the `client` instead. We recommend using it in
`liveblocks.config.ts` and re-exporting your typed hooks like below.
While [`createRoomContext`](#createRoomContext) offers APIs for interacting with
rooms (e.g. Presence, Storage, and Comments),
[`createLiveblocksContext`](#createLiveblocksContext) offers APIs for
interacting with Liveblocks features that are not tied to a specific room (e.g.
Notifications).
```tsx file="liveblocks.config.ts"
import { createClient } from "@liveblocks/client";
import { createRoomContext, createLiveblocksContext } from "@liveblocks/react";
const client = createClient({
// publicApiKey: "",
// authEndpoint: "/api/liveblocks-auth",
// throttle: 100,
});
// ...
export const { RoomProvider } = createRoomContext(client);
export const {
LiveblocksProvider,
useInboxNotifications,
// Other hooks
// ...
} = createLiveblocksContext(client);
```
### useClient [@badge=LiveblocksProvider]
Returns the [`client`](/docs/api-reference/liveblocks-client#createClient) of
the nearest [`LiveblocksProvider`][] above in the React component tree.
```ts
import { useClient } from "@liveblocks/react/suspense";
const client = useClient();
```
_None_
The [Liveblocks client](/docs/api-reference/liveblocks-client#createClient)
instance from the nearest [`LiveblocksProvider`][].
### useErrorListener [@badge=LiveblocksProvider]
Listen to potential Liveblocks errors. Examples of errors include room
connection errors, errors creating threads, and errors deleting notifications.
Each error has a `message` string, and a `context` object which has different
values for each error type. `context` always contains an error `type` and
`roomId`.
```ts
import { useErrorListener } from "@liveblocks/react/suspense";
useErrorListener((error) => {
// { message: "You don't have access to this room", context: { ... }}
console.error(error);
});
```
There are many different errors, and each can be handled separately by checking
the value of `error.context.type`. Below we’ve listed each error and the context
it provides.
```ts title="All error types" isCollapsable isCollapsed
import { useErrorListener } from "@liveblocks/react/suspense";
useErrorListener((error) => {
switch (error.context.type) {
// Can happen if you use Presence, Storage, or Yjs
case "ROOM_CONNECTION_ERROR": {
const { code } = error.context;
// -1 = Authentication error
// 4001 = You don't have access to this room
// 4005 = Room was full
// 4006 = Room ID has changed
break;
}
// Can happen if you use Comments or Notifications
case "CREATE_THREAD_ERROR":
const { roomId, threadId, commentId, body, metadata } = error.context;
break;
case "DELETE_THREAD_ERROR":
const { roomId, threadId } = error.context;
break;
case "EDIT_THREAD_METADATA_ERROR":
const { roomId, threadId, metadata } = error.context;
break;
case "MARK_THREAD_AS_RESOLVED_ERROR":
case "MARK_THREAD_AS_UNRESOLVED_ERROR":
const { roomId, threadId } = error.context;
break;
case "CREATE_COMMENT_ERROR":
case "EDIT_COMMENT_ERROR":
const { roomId, threadId, commentId, body } = error.context;
break;
case "DELETE_COMMENT_ERROR":
const { roomId, threadId, commentId } = error.context;
break;
case "ADD_REACTION_ERROR":
case "REMOVE_REACTION_ERROR":
const { roomId, threadId, commentId, emoji } = error.context;
break;
case "MARK_INBOX_NOTIFICATION_AS_READ_ERROR":
const { inboxNotificationId, roomId } = error.context;
break;
case "DELETE_INBOX_NOTIFICATION_ERROR":
const { roomId } = error.context;
break;
case "MARK_ALL_INBOX_NOTIFICATIONS_AS_READ_ERROR":
case "DELETE_ALL_INBOX_NOTIFICATIONS_ERROR":
break;
case "UPDATE_ROOM_SUBSCRIPTION_SETTINGS_ERROR":
const { roomId } = error.context;
break;
default:
// Ignore any error from the future
break;
}
});
```
A callback function that will be called when a Liveblocks error occurs. The
error object contains a message and context with error-specific information.
## AI Copilots
### useAiChats [@badge=LiveblocksProvider]
Returns a paginated list of AI chats created by the current user. Initially
fetches the latest 50 chats.
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
```tsx
import { useAiChats } from "@liveblocks/react";
const { chats, error, isLoading } = useAiChats();
```
Optional query to filter chats by metadata values or absence of metadata
keys. [Learn more](/docs/api-reference/liveblocks-react#useAiChats-query)
An array of AI chats created by the current user.
Whether the chats are currently being loaded.
Any error that occurred while loading the chats. [Learn
more](/docs/api-reference/liveblocks-react#useAiChats-error-handling).
Whether all available chats have been fetched. [Learn
more](/docs/api-reference/liveblocks-react#useAiChats-pagination).
A function to fetch more chats. [Learn
more](/docs/api-reference/liveblocks-react#useAiChats-pagination).
Whether more chats are currently being fetched. [Learn
more](/docs/api-reference/liveblocks-react#useAiChats-pagination).
Any error that occurred while fetching more chats. [Learn
more](/docs/api-reference/liveblocks-react#useAiChats-pagination).
##### List the user's chats and switch between them
You can use the [`AiChat`](/docs/api-reference/liveblocks-react-ui#AiChat)
component alongside the hook to create an AI chat switcher. Below, each button
displays the chat's automatically generated title, and chats can be deleted with
[`useDeleteAiChat`](#useDeleteAiChat).
```tsx
import { useState } from "react";
import { AiChat } from "@liveblocks/react-ui";
import { useAiChats } from "@liveblocks/react";
function Chats() {
// +++
const { chats, error, isLoading } = useAiChats();
const [chatId, setChatId] = useState();
const deleteChat = useDeleteAiChat();
// +++
if (isLoading) {
return
Loading...
;
}
if (error) {
return
Error: {error.message}
;
}
return (
// +++
{chats.map((chat) => (
))}
// +++
// +++
// +++
);
}
```
#### Querying chats [#useAiChats-query]
It’s possible to return chats that match a certain query with the `query`
option. You can filter by metadata values, or by the absence of a metadata key.
Returned chats must match the entire query.
```tsx
import { useAiChats } from "@liveblocks/react";
// Filter by metadata values and by absence of a key
const { chats } = useAiChats({
query: {
metadata: {
// Match chats that are of type 'temporary'
type: "temporary",
// Match chats that have all of these tags
tag: ["urgent", "billing"],
// Match chats where the "archived" key does not exist
archived: null,
},
},
});
```
#### Pagination [#useAiChats-pagination]
By default, the `useAiChats` hook returns up to 50 chats. To fetch more, the
hook provides additional fields for pagination, similar to [`useThreads`][].
```tsx
import { useAiChats } from "@liveblocks/react";
const {
chats,
isLoading,
error,
+++
hasFetchedAll,
fetchMore,
isFetchingMore,
fetchMoreError,
+++
} = useAiChats();
```
- `hasFetchedAll` indicates whether all available AI chats have been fetched.
- `fetchMore` loads up to 50 more AI chats, and is always safe to call.
- `isFetchingMore` indicates whether more AI chats are being fetched.
- `fetchMoreError` returns error statuses resulting from fetching more.
##### Pagination example [#useAiChats-pagination-example]
The following example demonstrates how to use the `fetchMore` function to
implement a “Load More” button, which fetches additional AI chats when clicked.
The button is disabled while fetching is in progress.
```tsx
import { AiChat } from "@liveblocks/react-ui";
import { useAiChats } from "@liveblocks/react";
function Inbox() {
const { chats, hasFetchedAll, fetchMore, isFetchingMore } = useAiChats();
return (
);
}
```
#### Error handling [#useAiChats-error-handling]
Error handling is another important aspect to consider when using the
`useAiChats` hook. The `error` and `fetchMoreError` fields provide information
about any errors that occurred during the initial fetch or subsequent fetch
operations, respectively. You can use these fields to display appropriate error
messages to the user and implement retry mechanisms if needed.
The following example shows how to display error messages for both initial
loading errors and errors that occur when fetching more inbox notifications.
```tsx
import { AiChat } from "@liveblocks/react-ui";
import { useAiChats } from "@liveblocks/react";
function Inbox() {
const { chats, error, fetchMore, fetchMoreError } = useAiChats();
// Handle error if the initial load failed.
// The `error` field is not returned by the Suspense hook as the error is thrown to nearest ErrorBoundary
// +++
if (error) {
return (
Error loading AI chats: {error.message}
);
}
// +++
return (
{chats.map((chat) => (
))}
{fetchMoreError && (
Error loading more AI chats: {fetchMoreError.message}
)}
);
}
```
### useAiChat
Returns information about an AI chat, for example its title and metadata. Titles
are automatically generated from the content of the first user message in a
chat, and the AI’s response.
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
```tsx
import { useAiChat } from "@liveblocks/react";
const { chat, error, isLoading } = useAiChat("my-chat-id");
```
The ID of the AI chat to retrieve information for.
The AI chat object containing title, metadata, and other properties.
Whether the chat information is currently being loaded.
Any error that occurred while loading the chat information.
#### Displaying a default title
If `chat.title` is `undefined` after an `isLoading` check, that means the title
has not been set yet. You can display a default title in this case, and the
title will be displayed once generated.
```tsx
import { useAiChat } from "@liveblocks/react";
function ChatTitle() {
const { chat, error, isLoading } = useAiChat("my-chat-id");
if (isLoading || error) {
return null;
}
// +++
return
{chat.title || "Untitled chat"}
;
// +++
}
```
### useCreateAiChat
Returns a function that creates an AI chat.
```tsx
import { useCreateAiChat } from "@liveblocks/react/suspense";
const createAiChat = useCreateAiChat();
createAiChat("my-ai-chat");
```
_None_
A function that creates an AI chat. Can be called with either a string ID or
an options object containing `id`, optional `title`, and optional
`metadata`.
#### Create a chat with a custom title and metadata
You can optionally set a `title` with `useCreateAiChat`, which prevents the AI
auto-generating a title from the first messages. Additionally, you can choose to
set custom `metadata` for the chat, strings or arrays of strings.
```tsx
import { useCreateAiChat } from "@liveblocks/react/suspense";
const createAiChat = useCreateAiChat();
createAiChat({
id: "my-ai-chat",
// +++
title: "My AI Chat",
metadata: {
color: "red",
tags: ["product", "engineering"],
},
// +++
});
```
### useDeleteAiChat
Returns a function that deletes an AI chat by its ID. Use in conjunction with
[`useAiChats`](#useAiChats) to
[loop through each chat](/docs/api-reference/liveblocks-react#List-the-user's-chats-and-switch-between-them)
and add a delete button.
```tsx
import { useDeleteAiChat } from "@liveblocks/react/suspense";
const deleteAiChat = useDeleteAiChat();
deleteAiChat("my-chat-id");
```
_None_
A function that deletes an AI chat by its ID.
### useSendAiMessage
Returns a function that sends a message to an AI chat, identified by its ID.
Useful for
[creating suggestions in empty inside chats](/docs/api-reference/liveblocks-react-ui#AiChat-placeholder)
and sending messages on behalf of the user.
```tsx
import { useSendAiMessage } from "@liveblocks/react";
const sendAiMessage = useSendAiMessage("my-chat-id");
sendAiMessage("Hello!");
```
Remember to [set your copilot ID]() otherwise the default copilot will be used.
```tsx
const sendAiMessage = useSendAiMessage("my-chat-id", {
// +++
copilotId: "co_h7GBa3...",
// +++
});
```
Optional. The ID of the AI chat to send messages to. Can also be provided
when calling the returned function.
Optional configuration object.
Optional. The ID of the copilot to use for sending the message.
A function that sends a message to an AI chat. Can be called with either a
string message or an options object containing `text`, optional `chatId`,
and optional `copilotId`.
#### Setting options when sending a message
Optionally you can set options when sending a message, instead of when creating
the hook. Alternatively, you can also override or complete the hook’s options
when calling the function by passing an object to it.
```tsx
import { useSendAiMessage } from "@liveblocks/react";
// Setting a `chatId` and `copilotId`
const sendAiMessage = useSendAiMessage("my-chat-id", {
copilotId: "co_shSm8f...",
});
// Sends to initial `chatId` and `copilotId`
sendAiMessage("Hello!");
// Overwrites the `copilotId` just for this message
sendAiMessage({
text: "Hello world",
// +++
copilotId: "co_Xpksa9...",
// +++
});
// Overwrites the `chatId` just for this message
sendAiMessage({
text: "Hello world",
// +++
chatId: "my-other-chat-id",
// +++
});
```
You can even skip setting the `chatId` and `copilotId` in the hook, and just
pass them in the function.
```tsx
// +++
const sendAiMessage = useSendAiMessage();
// +++
sendAiMessage({
text: "Hello world",
chatId: "my-other-chat-id",
});
```
#### Get the created message object
If necessary, you can also access the newly created message object.
```tsx
import { useSendAiMessage } from "@liveblocks/react";
const sendAiMessage = useSendAiMessage("my-chat-id");
const message = sendAiMessage("Hello world");
// { id: "ms_gw1wEn...", chatId: "my-chat-id", content: [...], ...}
console.log(message);
```
### useAiChatMessages
Returns a list of every message in an AI chat, identified by its ID. Updates in
realtime using WebSockets.
```tsx
import { useAiChatMessages } from "@liveblocks/react";
const { messages, error, isLoading } = useAiChatMessages("my-chat-id");
```
The ID of the AI chat to retrieve messages from.
An array of messages in the AI chat.
Whether the messages are currently being loaded.
Any error that occurred while loading the messages.
### useAiChatStatus
Returns the status of an AI chat, indicating whether it’s disconnected, loading,
idle or actively generating content. This is a convenience hook that derives its
state from the latest assistant message in the chat.
```tsx
import { useAiChatStatus } from "@liveblocks/react";
const { status, partType, toolName } = useAiChatStatus("my-chat-id");
```
The ID of the AI chat.
The current synchronization status of the chat. When disconnected the AI
service is not available.
The type of content being generated.
The name of the tool being invoked. If no tool is currently being called,
returns `undefined`.
### RegisterAiKnowledge
Adds knowledge to all AI features on the page. AI will understand the
information you pass, and will answer questions or call tools based on it. This
is particularly helpful for passing user info, app state, and other small
contextual knowledge.
```tsx
```
Each knowledge source has a `description` string, and a `value` which can be
either a string, object, array or JSON-serializable value that provides
meaningful context for your use case. The AI uses this data, along with the
accompanying description, to better understand and respond to user queries or
perform actions based on the supplied context. These components can be placed
anywhere in your app, so long as they’re under
[`LiveblocksProvider`](/docs/api-reference/liveblocks-react#LiveblocksProvider).
```tsx
import { AiChat } from "@liveblocks/react-ui";
import { RegisterAiKnowledge } from "@liveblocks/react";
function Chat() {
return (
<>
// +++
// +++
>
);
}
```
#### Pass in assorted context [#RegisterAiKnowledge-context]
Passing the AI context about the current datetime, the user’s language, the page
the user’s visiting, and navigable pages on your website, is an effective method
for improving your chat’s replies.
```tsx
import { RegisterAiKnowledge } from "@liveblocks/react";
function Chat() {
return (
<>
// +++
// +++
>
);
}
```
When building your app, it’s worth considering which app-specific context will
be helpful, for example the user’s payment plan, or a list of their projects.
#### Pass in user data from your auth provider [#RegisterAiKnowledge-user]
You can pass in knowledge from your auth provider, for example with
[`useUser`](https://clerk.com/docs/hooks/use-user) from
[Clerk](https://clerk.com). You can tell AI that the state is loading in a
simple string, and it will understand.
```tsx
import { RegisterAiKnowledge } from "@liveblocks/react";
import { useUser } from "@clerk/clerk-react";
function Chat() {
// +++
const { isSignedIn, user, isLoaded } = useUser();
// +++
return (
// +++
// +++
);
}
```
#### Pass in assorted data from fetching hooks [#RegisterAiKnowledge-fetching]
You can pass in knowledge from data fetching hooks such as with
[`useSWR`](https://swr.vercel.app/docs/getting-started) from
[SWR](https://swr.vercel.app/). You can tell AI that the state is loading in a
simple string, and it will understand.
```tsx
import { RegisterAiKnowledge } from "@liveblocks/react";
import useSWR from "swr";
function Chat() {
// +++
const { data, error, isLoading } = useSWR(`/important-data`, fetcher);
// +++
return (
// +++
// +++
);
}
const fetcher = (...args) => fetch(...args).then((res) => res.json());
```
#### Pass in text editor document data [#RegisterAiKnowledge-text-editor]
You can pass in knowledge from your text editor, for example when using
[Liveblocks Tiptap](/docs/api-reference/liveblocks-react-tiptap).
```tsx
import { RegisterAiKnowledge } from "@liveblocks/react-ui";
import { useLiveblocksExtension } from "@liveblocks/react-tiptap";
import { useEditor, EditorContent } from "@tiptap/react";
function TextEditor() {
const liveblocks = useLiveblocksExtension();
// +++
const editor = useEditor({
extensions: [
liveblocks,
// ...
],
});
// +++
return (
// +++
// +++
);
}
```
As well as `editor.getHTML()`, `editor.getJSON()` and `editor.getText()` are
also available when using Tiptap. Its worth trying them all, in case your AI
model understands one of them better than the others.
{/* TODO how to make tools where you can write to the text editor */}
#### Pass in comment data [#RegisterAiKnowledge-storage]
You can also pass in knowledge from your custom Liveblocks Comments app with
[`useThreads`](/docs/api-reference/liveblocks-react#useThreads). This way, your
AI chat will understand the context in the current room.
```tsx
import { RegisterAiKnowledge, useThreads } from "@liveblocks/react";
function Comments() {
// +++
const { threads, isLoading, error } = useThreads();
// +++
return (
// +++
// +++
{threads.map((thread) => (
)}
);
}
```
#### Pass in storage data [#RegisterAiKnowledge-storage]
You can also pass in knowledge from your custom Liveblocks storage app with
[`useStorage`](/docs/api-reference/liveblocks-react#useStorage). This way, your
AI chat will understand the context in the current room.
```tsx
import { RegisterAiKnowledge, useStorage } from "@liveblocks/react/suspense";
function Whiteboard() {
// +++
const shapes = useStorage((root) => root.shapes);
// +++
return (
// +++
// +++
{shapes.map((shape) => (
// ...
)}
);
}
```
#### Props [#RegisterAiKnowledge-props]
A clear description of what this knowledge represents. This helps the AI
understand the context and relevance of the provided information.
The actual data or information to share with the AI. Can be a string,
object, array, or any JSON-serializable information that offers context
relevant to your application or user.
Optional unique identifier for this knowledge source. If provided,
subsequent updates with the same ID will replace the previous knowledge.
Optional chat ID to scope this tool to a specific chat. If provided, the
tool will only be available to that chat.
### RegisterAiTool
Registers a tool that can be used by
[AI chats](/docs/api-reference/liveblocks-react-ui#AiChat) on the page. Tools
allow AI to autonomously run actions, render custom components, and show
confirmation or human-in-the-loop UIs within the chat.
```tsx
import { RegisterAiTool } from "@liveblocks/react";
import { defineAiTool } from "@liveblocks/client";
;
```
{/* TODO lots more info */}
[`defineAiTool`](/docs/api-reference/liveblocks-client#defineAiTool) is used to
create a tool definition, and you can supply `parameters` as a
[JSON Schema](https://json-schema.org/) that the AI can fill in. If you supply
an `execute` function the AI will call it. `render` is used to show UI inside
the chat. Below is an example of a tool that lets AI get the current weather in
a given location, then renders a component in the chat.
{/* TODO this all needs to be explained better */}
```tsx
function App() {
return (
<>
// +++
{
const { temperature, condition } = await __getWeather__(
args.location
);
return { data: { temperature, condition } };
},
render: ({ result }) => (
{result.data ? (
) : null}
),
})}
/>
// +++
>
);
}
```
#### Tool that sends a toast notification
The following snippet shows a tool that lets AI send a toast notification with
[Sonner](https://sonner.emilkowal.ski/), then adds a message in the chat with
[`AiTool`](/docs/api-reference/liveblocks-react-ui#AiTool), letting the user
know that a toast was sent.
```tsx
import { AiChat } from "@liveblocks/react-ui";
import { RegisterAiTool } from "@liveblocks/react";
import { defineAiTool } from "@liveblocks/client";
import { toast, Toaster } from "sonner";
function Chat() {
return (
<>
{
toast(message);
return {
data: { message },
description: "You sent a toast",
};
},
render: () => ,
})}
/>
>
);
}
```
#### Scoping a tool to a specific chat
Tools can be scoped to specific chats by providing a `chatId` prop. When scoped,
the tool will only be available to that specific chat.
```tsx
import { AiChat } from "@liveblocks/react-ui";
import { RegisterAiTool } from "@liveblocks/react";
import { defineAiTool } from "@liveblocks/client";
function Chat() {
return (
<>
// +++
// +++
>
);
}
```
#### Props [#RegisterAiTool-props]
Unique name for the tool. This is used internally to identify and manage the
tool.
The tool definition created with
[`defineAiTool`](/docs/api-reference/liveblocks-client#defineAiTool).
Optional chat ID to scope this tool to a specific chat. If provided, the
tool will only be available to that chat.
Whether this tool should be enabled. When set to `false`, the tool will not
be made available to the AI copilot for any new/future chat messages, but
will still allow existing tool invocations to be rendered that are part of
the historic chat record. When provided as a prop to `RegisterAiTool`, it
will take precedence over the value of the tool’s `enabled` value in
`defineAiTool`.
## Room
### RoomProvider
Makes a [`Room`][] available in the component hierarchy below. Joins the room
when the component is mounted, and automatically leaves the room when the
component is unmounted. When using
[Sync Datastore](/docs/platform/sync-datastore), initial Presence values for
each user, and Storage values for the room can be set.
```tsx
import { RoomProvider } from "@liveblocks/react/suspense";
function App() {
return {/* children */};
}
```
The unique ID for the current room. `RoomProvider` will join this room when
it loads. If the room doesn’t exist already it will automatically create the
room first then join. After setting up
[authentication](/docs/authentication) for your app, it can helpful to
decide on a naming pattern for your room IDs.
The initial Presence of the user entering the room. Each user has their own
presence, and this is readable for all other connected users. A user’s
Presence resets every time they disconnect. This object must be
JSON-serializable. This value is ignored after the first render. [Learn
more](#setting-initial-presence).
The initial Storage structure for the room when it’s joined for the first
time. This is only set a single time, when the room has not yet been
populated. This object must contain [conflict-free live
structures](/docs/api-reference/liveblocks-client#Storage). This value is
ignored after the first render, and if Storage for the current room has
already been created. [Learn more](#setting-initial-storage).
Whether the room immediately connects to Liveblocks servers. This value is
ignored after the first render.
Preferred storage engine version to use when creating the room. Only takes
effect if the room doesn’t exist yet. The v2 Storage engine supports larger
documents, is more performant, has native streaming support, and will become
the default in the future. [Learn
more](/docs/guides/about-the-new-storage-engine).
#### Setting initial Presence [#setting-initial-presence]
Presence is used for storing temporary user-based values, such as a user’s
cursor coordinates, or their current selection. Each user has their own
presence, and this is readable for all other connected users. Set your initial
Presence value by using `initialPresence`.
```tsx
import { RoomProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
Each user’s Presence resets every time they disconnect, as this is only meant
for temporary data. Any JSON-serializable object is allowed (the `JsonObject`
type).
#### Setting initial Storage [#setting-initial-storage]
Storage is used to store permanent data that’s used in your application, such as
shapes on a whiteboard, nodes on a flowchart, or text in a form. The first time
a room is entered, you can set an initial value by using `initialStorage`.
`initialStorage` is only read and set a single time, unless a new top-level
property is added.
```tsx
import { LiveList, LiveObject, LiveMap } from "@liveblocks/client";
import { RoomProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
If a new top-level property is added to `initialStorage`, the next time a user
connects, the new property will be created. Other properties will be unaffected.
Any
[conflict-free live structures](/docs/api-reference/liveblocks-client#Storage)
and JSON-serializable objects are allowed (the `LsonObject` type).
#### Speed up connecting to a room [#speed-up-connecting-to-a-room]
To speed up connecting to a room, you can call
[`Liveblocks.prewarmRoom`](/docs/api-reference/liveblocks-node#get-rooms-roomId-prewarm)
on the server, which will warm up a room for the next 10 seconds. Triggering
this directly before a user navigates to a room is an easy to way use this API.
Here’s a Next.js server actions example, showing how to trigger prewarming with
`onPointerDown`.
```ts title="actions.ts"
"use server";
import { Liveblocks } from "@liveblocks/node";
const liveblocks = new Liveblocks({
secret: "{{SECRET_KEY}}",
});
export async function prewarmRoom(roomId: string) {
// +++
await liveblocks.prewarmRoom(roomId);
// +++
}
```
```tsx title="RoomLink.tsx"
"use client";
import { prewarmRoom } from "../actions";
import Link from "next/link";
export function JoinButton({ roomId }: { roomId: string }) {
return (
// +++
prewarmRoom(roomId)}>
// +++
{roomId}
);
}
```
`onPointerDown` is slightly quicker than `onClick` because it triggers before
the user releases their pointer.
### createRoomContext
This used to be the default way to start your app, but now it’s recommend for
advanced usage only. We generally recommend using [`LiveblocksProvider`][] and
following [typing your data with the Liveblocks interface](#Typing-your-data),
unless you need to define multiple room types in your application.
Creates a [`RoomProvider`][] and a set of typed hooks to use in your app. Note
that any `RoomProvider` created in this way does not need to be nested in
[`LiveblocksProvider`][], as it already has access to the `client`. We generally
recommend typing your app using the newer method instead. When using
`createRoomContext` it can be helpful to use it in `liveblocks.config.ts` and
re-export your typed hooks as below.
```tsx file="liveblocks.config.ts"
import { createClient } from "@liveblocks/client";
import { createRoomContext } from "@liveblocks/react";
const client = createClient({
// publicApiKey: "",
// authEndpoint: "/api/liveblocks-auth",
});
type Presence = {};
type Storage = {};
type UserMeta = {};
type RoomEvent = {};
type ThreadMetadata = {};
type CommentMetadata = {};
// +++
export const {
RoomProvider,
useMyPresence,
// Other hooks
// ...
} = createRoomContext<
Presence,
Storage,
UserMeta,
RoomEvent,
ThreadMetadata,
CommentMetadata
>(client);
// +++
```
#### Suspense with createRoomContext [#createRoomContext-Suspense]
To use the React suspense version of our hooks with `createRoomContext`, you can
export from the `suspense` property instead.
```tsx file="liveblocks.config.ts"
import { createClient } from "@liveblocks/client";
import { createRoomContext } from "@liveblocks/react";
const client = createClient({
// publicApiKey: "",
// authEndpoint: "/api/liveblocks-auth",
});
type Presence = {};
type Storage = {};
type UserMeta = {};
type RoomEvent = {};
type ThreadMetadata = {};
type CommentMetadata = {};
export const {
// +++
suspense: {
RoomProvider,
useMyPresence,
// Other suspense hooks
// ...
},
// +++
} = createRoomContext<
Presence,
Storage,
UserMeta,
RoomEvent,
ThreadMetadata,
CommentMetadata
>(client);
```
#### Typing createRoomContext
To type your hooks, you can pass multiple different types to
`createRoomContext`. A full explanation is in the code snippet below.
```tsx file="liveblocks.config.ts" isCollapsable isCollapsed
import { createClient } from "@liveblocks/client";
import { createRoomContext } from "@liveblocks/react";
const client = createClient({
// publicApiKey: "",
// authEndpoint: "/api/liveblocks-auth",
});
// Presence represents the properties that exist on every user in the Room
// and that will automatically be kept in sync. Accessible through the
// `user.presence` property. Must be JSON-serializable.
type Presence = {
// cursor: { x: number, y: number } | null,
// ...
};
// Optionally, Storage represents the shared document that persists in the
// Room, even after all users leave. Fields under Storage typically are
// LiveList, LiveMap, LiveObject instances, for which updates are
// automatically persisted and synced to all connected clients.
type Storage = {
// animals: LiveList,
// ...
};
// Optionally, UserMeta represents static/readonly metadata on each user, as
// provided by your own custom auth back end (if used). Useful for data that
// will not change during a session, like a user’s name or avatar.
// type UserMeta = {
// id?: string, // Accessible through `user.id`
// info?: Json, // Accessible through `user.info`
// };
// Optionally, the type of custom events broadcast and listened to in this
// room. Use a union for multiple events. Must be JSON-serializable.
// type RoomEvent = {};
// Optionally, when using Comments, ThreadMetadata represents metadata on
// each thread. Can only contain booleans, strings, and numbers.
// export type ThreadMetadata = {
// pinned: boolean;
// quote: string;
// time: number;
// };
export const {
RoomProvider,
useMyPresence,
useStorage,
// Other hooks
// ...
} = createRoomContext<
Presence,
Storage
/* UserMeta, RoomEvent, ThreadMetadata */
>(client);
```
### useRoom [@badge=RoomProvider]
Returns the [`Room`][] of the nearest [`RoomProvider`][] above in the React
component tree.
```ts
import { useRoom } from "@liveblocks/react/suspense";
const room = useRoom();
```
Will throw when used outside of a [`RoomProvider`][]. If you don’t want this
hook to throw when used outside of a Room context (for example to write
components in a way that they can be used both inside and outside of a
Liveblocks room), you can use the `{ allowOutsideRoom }` option:
```ts
import { useRoom } from "@liveblocks/react/suspense";
const room = useRoom({ allowOutsideRoom: true }); // Possibly `null`
```
Whether the hook should return `null` instead of throwing when used outside
of a [`RoomProvider`][] context.
The Room instance from the nearest [`RoomProvider`][]. Returns `null` if
`allowOutsideRoom` is `true` and the hook is used outside of a room.
### useIsInsideRoom [@badge=Both]
Returns a boolean, `true` if the hook was called inside a [`RoomProvider`][]
context, and `false` otherwise.
```ts
import { useIsInsideRoom } from "@liveblocks/react/suspense";
const isInsideRoom = useIsInsideRoom();
```
_None_
`true` if the hook was called inside a [`RoomProvider`][] context, `false`
otherwise.
#### Displaying different components inside rooms
`useIsInsideRoom` is helpful for rendering different components depending on
whether they’re inside a room, or not. One example is a header component that
only displays a live avatar stack when users are connected to the room.
```tsx
import { useIsInsideRoom, useOthers } from "@liveblocks/react/suspense";
function Header() {
// +++
const isInsideRoom = useIsInsideRoom();
// +++
return (
// +++
{isInsideRoom ? : null}
// +++
);
}
function LiveAvatars() {
const others = useOthers();
return others.map((other) => );
}
```
Here’s how the example above would render in three different
[`LiveblocksProvider`](/docs/api-reference/liveblocks-react#LiveblocksProvider)
and [`RoomProvider`](/docs/api-reference/liveblocks-react#RoomProvider)
contexts.
```tsx
// 👥👤 Live avatar stack and your avatar
// 👤 Just your avatar
// 👤 Just your avatar
```
### useStatus [@badge=RoomProvider]
Returns the current WebSocket connection status of the room, and will re-render
your component whenever it changes.
```ts
import { useStatus } from "@liveblocks/react/suspense";
const status = useStatus();
```
_None_
The current WebSocket connection status of the room.
### useSyncStatus [@badge=Both]
Returns the current synchronization status of Liveblocks, and will re-render
your component whenever it changes. This includes any part of Liveblocks that
may be synchronizing local changes to the server, including (any room’s)
Storage, text editors, threads, or notifications.
A `{ smooth: true }` option is also available, which prevents quick changes
between states, making it ideal for
[rendering a synchronization badge in your app](#display-synchronization-badge).
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
```ts
import { useSyncStatus } from "@liveblocks/react/suspense";
// "synchronizing" | "synchronized"
const syncStatus = useSyncStatus();
```
Optional configuration object.
When `true`, prevents quick changes between states by delaying the
transition from "synchronizing" to "synchronized" until 1 second has passed
after the final change.
The current synchronization status of Liveblocks.
#### Display a synchronization badge [#display-synchronization-badge]
Passing `{ smooth: true }` prevents the status changing from `"synchronizing"`
to `"synchronized"` until 1 second has passed after the final change. This means
it’s ideal for rendering a synchronization status badge, as it won’t flicker in
a distracting manner when changes are made in quick succession.
```tsx
import { useSyncStatus } from "@liveblocks/react/suspense";
function StorageStatusBadge() {
const syncStatus = useSyncStatus({ smooth: true });
return
;
}
```
#### Prevent users losing unsaved changes [#use-sync-status-prevent-users-losing-unsaved-changes]
Liveblocks usually synchronizes milliseconds after a local change, but if a user
immediately closes their tab, or if they have a slow connection, it may take
longer for changes to synchronize. Enabling `preventUnsavedChanges` will stop
tabs with unsaved changes closing, by opening a dialog that warns users. In
usual circumstances, it will very rarely trigger.
```tsx
function Page() {
return (
...
);
}
```
More specifically, this option triggers when:
- There are unsaved changes after calling any hooks or methods, in all of our
products.
- There are unsaved changes in a
[Text Editor](/docs/ready-made-features/text-editor).
- There’s an unsubmitted comment in the
[Composer](/docs/api-reference/liveblocks-react-ui#Composer).
- The user has made changes and is currently offline.
Internally, this option uses the
[beforeunload event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
### useOthersListener [@badge=RoomProvider]
Calls the given callback when an “others” event occurs, when a user enters,
leaves, or updates their presence.
```ts
function App() {
useOthersListener(({ type, user, others }) => {
switch (type) {
case "enter":
// `user` has entered the room
break;
case "leave":
// `user` has left the room
break;
case "update":
// Presence for `user` has updated
break;
case "reset":
// Others list has been emptied
break;
}
});
}
```
A callback function that is called when an "others" event occurs. The event
object contains the error `type`, the `user` that triggered it, and the current
`others` in the room. Possible event types are:
- `enter` – A user has entered the room.
- `leave` – A user has left the room.
- `reset` – The others list has been emptied. This is the first event that
occurs when the room is entered. It also occurs when you’ve lost connection to
the room.
- `update` – A user’s presence data has been updated.
### useLostConnectionListener [@badge=RoomProvider]
Calls the given callback in the exceptional situation that a connection is lost
and reconnecting does not happen quickly enough.
This event allows you to build high-quality UIs by warning your users that the
app is still trying to re-establish the connection, for example through a toast
notification. You may want to take extra care in the mean time to ensure their
changes won’t go unsaved.
When this happens, this callback is called with the event `lost`. Then, once the
connection restores, the callback will be called with the value `restored`. If
the connection could definitively not be restored, it will be called with
`failed` (uncommon).
The [`lostConnectionTimeout`][] client option will determine how quickly this
event will fire after a connection loss (default: 5 seconds).
```ts
import { toast } from "my-preferred-toast-library";
function App() {
useLostConnectionListener((event) => {
switch (event) {
case "lost":
toast.warn("Still trying to reconnect...");
break;
case "restored":
toast.success("Successfully reconnected again!");
break;
case "failed":
toast.error("Could not restore the connection");
break;
}
});
}
```
Automatically unsubscribes when the component is unmounted. For a demonstration
of this behavior, see our [connection status example][].
A callback function that is called when a connection loss event occurs. The
event can be "lost", "restored", or "failed".
## Presence
Try the [Liveblocks DevTools extension](/devtools) to visualize your
collaborative experiences as you build them, in realtime.
### useMyPresence [@badge=RoomProvider]
Return the presence of the current user, and a function to update it.
Automatically subscribes to updates to the current user’s presence. Setting a
property will not replace the whole state, but will instead merge the property
into the existing state.
```ts
import { useMyPresence } from "@liveblocks/react/suspense";
const [myPresence, updateMyPresence] = useMyPresence();
updateMyPresence({ x: 0 });
updateMyPresence({ y: 0 });
// At the next render, "myPresence" will be equal to "{ x: 0, y: 0 }"
```
The current user’s presence data.
A function to update the current user’s presence. Accepts a partial presence
object and optional history options.
#### Adding presence to history
`updateMyPresence` accepts an optional argument to add a new item to the
undo/redo stack. See [`room.history`][] for more information.
```ts
updateMyPresence({ selectedId: "xxx" }, { addToHistory: true });
```
#### Other ways to use presence
`useMyPresence` is a more convenient way to update and view presence, rather
than using [`useSelf`][] and [`useUpdateMyPresence`][] in combination.
```tsx
const myPresence = useSelf((me) => me.presence);
const updateMyPresence = useUpdateMyPresence();
```
### useUpdateMyPresence [@badge=RoomProvider]
Returns a setter function to update the current user’s presence. Setting a
property will not replace the whole state, but will instead merge the property
into the existing state. Will trigger fewer renders than [`useMyPresence`][], as
it doesn’t update when presence changes.
```ts
import { useUpdateMyPresence } from "@liveblocks/react/suspense";
const updateMyPresence = useUpdateMyPresence();
updateMyPresence({ y: 0 });
updateMyPresence({ x: 0 });
// Presence will be { x: 0, y: 0 }
```
_None_
A function to update the current user's presence. Accepts a partial presence
object and optional history options.
#### Adding presence to history
`updateMyPresence` accepts an optional argument to add a new item to the
undo/redo stack. See [`room.history`][] for more information.
```ts
updateMyPresence({ selectedId: "xxx" }, { addToHistory: true });
```
### useSelf [@badge=RoomProvider]
Returns the current user once it is connected to the room, and automatically
subscribes to updates to the current user.
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
```ts
import { useSelf } from "@liveblocks/react/suspense";
const currentUser = useSelf();
// {
// connectionId: 1,
// presence: { cursor: { x: 27, y: -8 } },
// }
const currentUser = useSelf((me) => me.presence.cursor);
// { x: 27, y: -8 }
```
The benefit of using a selector is that it will only update your component if
that particular selection changes. For full details, see [how selectors work][].
Optional selector function to extract specific data from the current user.
If not provided, returns the entire user object.
The current user object or the selected data from the user. Returns `null`
if not connected to the room (in non-Suspense version).
#### Checking user permissions
It’s possible to check if a user has a specific permission by using the
`canWrite` and `canComment` properties of the `User` object. This is set via
your [room permissions](/docs/authentication#Room-permissions).
```ts
import { useSelf } from "@liveblocks/react/suspense";
function PermissionBadge() {
const canWrite = useSelf((me) => me.canWrite);
if (canWrite) {
return
✏️ Full access
;
}
return
👀 Read-only access
;
}
```
This is particularly helpful in combination with text editors, such as
[Tiptap](/docs/api-reference/liveblocks-react-tiptap) as you can prevent
read-only users from editing the document.
```tsx
import { useSelf } from "@liveblocks/react/suspense";
import { useLiveblocksExtension } from "@liveblocks/react-tiptap";
import { useEditor, EditorContent } from "@tiptap/react";
function TextEditor() {
const liveblocks = useLiveblocksExtension();
// +++
const canWrite = useSelf((me) => me.canWrite);
// +++
const editor = useEditor({
// +++
editable: canWrite,
// +++
extensions: [
liveblocks,
// ...
],
});
return (
);
}
```
### useOthers [@badge=RoomProvider]
Extracts data from the list of other users currently in the same Room, and
automatically subscribes to updates on the selected data. For full details, see
[how selectors work][].
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
The `others` argument to the `useOthers` selector function is an _immutable_
array of Users.
```tsx
// ✅ Rerenders only if the number of users changes
const numOthers = useOthers((others) => others.length);
// ✅ Rerenders only if someone starts or stops typing
const isSomeoneTyping = useOthers((others) =>
others.some((other) => other.presence.isTyping)
);
// ✅ Rerenders only if actively typing users are updated
const typingUsers = useOthers(
(others) => others.filter((other) => other.presence.isTyping),
shallow // 👈
);
```
One caveat with this API is that selecting a subset of data for each user
quickly becomes tricky. When you want to select and get updates for only a
particular subset of each user’s data, we recommend using the
[`useOthersMapped`][] hook instead, which is optimized for this use case.
```tsx
// ❌ Mapping is hard to get right with this hook
const cursors = useOthers(
(others) => others.map((other) => other.presence.cursor),
shallow
);
// ✅ Better to use useOthersMapped
const cursors = useOthersMapped((other) => other.presence.cursor);
```
When called without arguments, returns the user list and updates your component
whenever _anything_ in it changes. This might be way more often than you want!
```tsx
const others = useOthers(); // ⚠️ Caution, might rerender often!
// [
// { connectionId: 2, presence: { cursor: { x: 27, y: -8 } } },
// { connectionId: 3, presence: { cursor: { x: 0, y: 19 } } },
// ]
```
In production-ready apps, you likely want to avoid calling `useOthers` without
arguments.
Optional selector function to extract specific data from the others array.
If not provided, returns the entire others array.
Optional equality function to determine if the selected data has changed.
Defaults to strict equality comparison.
The others array or the selected data from the others array. Returns `null`
if not connected to the room (in non-Suspense version).
### useOthersMapped [@badge=RoomProvider]
Extract data using a [selector][] for every user in the room, and subscribe to
all changes to the selected data. A [Suspense version][] of this hook is also
available. The key difference with [`useOthers`][] is that the selector (and the
optional comparison function) work at the _item_ level, like doing a `.map()`
over the others array.
```tsx
// Example 1
const others = useOthersMapped((other) => other.presence.cursor);
// [
// [2, { x: 27, y: -8 }],
// [3, { x: 0, y: 19 }],
// ]
// Example 2
const others = useOthersMapped(
(other) => ({
avatar: other.info.avatar,
isTyping: other.presence.isTyping,
}),
shallow // 👈
);
// [
// [2, { avatar: 'https://...', isTyping: true }],
// [3, { avatar: null, isTyping: false }],
// ]
```
Returns an array where each item is a pair of `[connectionId, data]`. For
pragmatic reasons, the results are keyed by the `connectionId`, because in most
cases you’ll want to iterate over the results and draw some UI for each, which
in React requires you to use a `key={connectionId}` prop.
```tsx
const others = useOthersMapped((other) => other.presence.cursor);
// In JSX
return (
<>
{others.map(([connectionId, cursor]) => (
))}
>
);
```
A selector function to extract specific data from each user in the others
array.
Optional equality function to determine if the selected data for a user has
changed. Defaults to strict equality comparison.
An array of tuples where each item is a pair of `[connectionId,
selectedData]`. Returns `null` if not connected to the room (in non-Suspense
version).
### useOthersConnectionIds [@badge=RoomProvider]
Returns an array of connection IDs (numbers), and rerenders automatically when
users join or leave. This hook is useful in particular in combination with the
[`useOther`][] (singular) hook, to implement high-frequency rerendering of
components for each user in the room, e.g. cursors. See the [`useOther`][]
(singular) documentation below for a full usage example.
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
```tsx
import { useOthersConnectionIds } from "@liveblocks/react/suspense";
// [2, 4, 7]
const connectionIds = useOthersConnectionIds();
```
An array of connection IDs for all other users in the room. Returns `null`
if not connected to the room (in non-Suspense version).
#### Another way to fetch connection IDs
This hook is similar to using [`useOthers`][] and calling `.map()` on the
result.
```tsx
import { useOthers, shallow } from "@liveblocks/react/suspense";
// [2, 4, 7]
const connectionIds = useOthers(
(others) => others.map((other) => other.connectionId),
shallow
);
```
### useOther [@badge=RoomProvider]
Extract data using a [selector][] for one specific user in the room, and
subscribe to all changes to the selected data.
[Suspense](/docs/api-reference/liveblocks-react#Suspense-hooks) and
[regular](/docs/api-reference/liveblocks-react#Regular-hooks) versions of this
hook are available.
```tsx
import { useOther } from "@liveblocks/react/suspense";
// ✅ Rerenders when this specific user’s isTyping changes (but not when their cursor changes)
const isTyping = useOther(
3, // User with connectionId 3
(user) => user.presence.isTyping
);
```
The reason this hook exists is to enable the most efficient rerendering model
for high-frequency updates to other’s presences, which is the following
structure:
```tsx file="Cursors.tsx"
const Cursors =
// +++
// (1) Wrap parent component in a memo and make sure it takes no props
React.memo(function () {
const othersConnectionIds = useOthersConnectionIds(); // (2)
// +++
return (
<>
{othersConnectionIds.map((connectionId) => (
))}
>
);
});
```
```tsx file="Cursor.tsx"
function Cursor({ connectionId }) {
// +++
const { x, y } = useOther(connectionId, (other) => other.presence.cursor); // (4)
// +++
return ;
}
```
1. Makes sure this whole component tree will never rerender beyond the first
time.
2. Makes sure the parent component only rerenders when users join/leave.
3. Makes sure each cursor remains associated to the same connection.
4. Makes sure each cursor rerenders whenever _its_ data changes only.
👉 A [Suspense version][] of this hook is also available, which will never
return `null`.
The connection ID of the specific user to extract data from.
A selector function to extract specific data from the user.
Optional equality function to determine if the selected data has changed.
Defaults to strict equality comparison.
The selected data from the specified user. Returns `null` if the user is not
found or not connected to the room (in non-Suspense version).
## Broadcast
### useBroadcastEvent [@badge=RoomProvider]
Returns a callback that lets you broadcast custom events to other users in the
room.
```ts
import { useBroadcastEvent } from "@liveblocks/react/suspense";
// +++
// On client A
const broadcast = useBroadcastEvent();
broadcast({ type: "EMOJI", emoji: "🔥" });
// +++
// On client B
useEventListener(({ event, user, connectionId }) => {
// ^^^^ Will be Client A
if (event.type === "EMOJI") {
// Do something
}
});
```
_None_
A function that broadcasts custom events to other users in the room.
### useEventListener [@badge=RoomProvider]
Listen to custom events sent by other people in the room via
[`useBroadcastEvent`][]. Provides the `event` along with the `connectionId` of
the user that sent the message. If an event was sent from the
[Broadcast to a room](/docs/api-reference/rest-api-endpoints#post-broadcast-event)
REST API, `connectionId` will be `-1`.
```ts
import { useEventListener } from "@liveblocks/react/suspense";
// On client A
const broadcast = useBroadcastEvent();
broadcast({ type: "EMOJI", emoji: "🔥" });
// +++
// On client B
useEventListener(({ event, user, connectionId }) => {
// ^^^^ Will be Client A
if (event.type === "EMOJI") {
// Do something
}
});
// +++
```
The `user` property will indicate which User instance sent the message. This
will typically be equal to one of the others in the room, but it can also be
`null` in case this event was broadcasted from the server, using the
[Broadcast Event API](https://liveblocks.io/docs/api-reference/rest-api-endpoints#post-broadcast-event).
Automatically unsubscribes when the component is unmounted.
A callback function that is called when a custom event is received. The
callback receives an object with the event data, user information, and
connection ID. Connection ID is always `-1` when receiving an event sent
from the server.
## Storage
Each room contains Storage, a conflict-free data store that multiple users can
edit at the same time. When users make edits simultaneously, conflicts are
resolved automatically, and each user will see the same state. Storage is ideal
for storing permanent document state, such as shapes on a canvas, notes on a
whiteboard, or cells in a spreadsheet.
### Data structures
Storage provides three different conflict-free data structures, which you can
use to build your application. All structures are permanent and persist when all
users have left the room, unlike [Presence](/docs/ready-made-features/presence)
which is temporary.
- [`LiveObject`][] - Similar to JavaScript object. Use this for storing records
with fixed key names and where the values don’t necessarily have the same
types. For example, a `Person` with a `name: string` and an `age: number`
field. If multiple clients update the same property simultaneously, the last
modification received by the Liveblocks servers is the winner.
- [`LiveList`][] - An ordered collection of items synchronized across clients.
Even if multiple users add/remove/move elements simultaneously, LiveList will
solve the conflicts to ensure everyone sees the same collection of items.
- [`LiveMap`][] - Similar to a JavaScript Map. Use this for indexing values that
all have the same structure. For example, to store an index of `Person` values
by their name. If multiple users update the same property simultaneously, the
last modification received by the Liveblocks servers is the winner.
### Typing Storage [#typing-storage]
To type the Storage values you receive, make sure to set your `Storage` type.
```ts
import { LiveList } from "@liveblocks/client";
declare global {
interface Liveblocks {
Storage: {
animals: LiveList;
};
}
}
```
You can then set an initial value in [`RoomProvider`][].
```tsx
import { LiveList } from "@liveblocks/client";
import { RoomProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
The type received in your Storage will match the type passed. Learn more under
[typing your data](#typing-your-data).
```tsx
import { useMutation } from "@liveblocks/react/suspense";
function App() {
const addAnimal = useMutation(({ storage }) => {
const animals = storage.get("animals");
// LiveList<["Fido"]>
console.log(animals);
animals.push("Felix");
// LiveList<["Fido", "Felix"]>
console.log(animals);
});
return ;
}
```
[`useStorage`][] will return an immutable copy of the data, for example a
`LiveList` is converted to an `array`, which makes it easy to render.
```tsx
import { useStorage } from "@liveblocks/react/suspense";
function App() {
const animals = useStorage((root) => root.animals);
// ["Fido", "Felix"]
console.log(animals);
return (
{animals.map((animal) => (
{animal}
))}
);
}
```
### Nesting data structures
All Storage data structures can be nested, allowing you to create complex trees
of conflict-free data.
```ts
import { LiveObject, LiveList, LiveMap } from "@liveblocks/client";
type Person = LiveObject<{
name: string;
pets: LiveList;
}>;
declare global {
interface Liveblocks {
Storage: {
people: LiveMap;
};
}
}
```
Here’s an example of setting `initialStorage` for this type.
```tsx
import { LiveObject, LiveList, LiveMap } from "@liveblocks/client";
import { RoomProvider } from "@liveblocks/react/suspense";
function App() {
return (
{/* children */}
);
}
```
Get the [Liveblocks DevTools extension](/devtools) to develop and debug your
application as you build it.
### useStorage [@badge=RoomProvider]
Extracts data from Liveblocks Storage state and automatically subscribes to
updates to that selected data. For full details, see [how selectors work][].
```tsx
// ✅ Rerenders if todos (or their children) change
const items = useStorage((root) => root.todos);
// ✅ Rerenders when todos are added or deleted
const numTodos = useStorage((root) => root.todos.length);
// ✅ Rerenders when the value of allDone changes
const allDone = useStorage((root) => root.todos.every((item) => item.done));
// ✅ Rerenders if any _unchecked_ todo items change
const uncheckedItems = useStorage(
(root) => root.todos.filter((item) => !item.done),
shallow // 👈
);
```
The `root` argument to the `useStorage` selector function is an _immutable_ copy
of your entire Liveblocks Storage tree. Think of it as the value you provided in
the `initialStorage` prop at the [`RoomProvider`][] level, but then
(recursively) converted to their “normal” JavaScript equivalents (objects,
arrays, maps) that are read-only.
From that immutable `root`, you can select or compute any value you like. Your
component will automatically get rerendered if the value you return differs from
the last rendered value.
This hook returns `null` while storage is still loading. To avoid that, use the
[Suspense version][].
It’s recommended to select only the subset of Storage data that your component
needs. This will avoid unnecessary rerenders that happen with overselection.
In order to select one item from a LiveMap within the storage tree with the
`useStorage` method, you can use the example below:
```ts
const key = "errands";
const myTodos = useStorage((root) => root.todoMap.get(key));
```
In order to query a LiveMap, and filter for specific values:
```ts
const myTodos = useStorage(
root => Array.from(root.todoMap.values()).filter(...),
shallow,
);
```
A selector function to extract specific data from the storage root. The root
is an immutable copy of your entire Liveblocks Storage tree.
Optional equality function to determine if the selected data has changed.
Defaults to strict equality comparison.
The selected data from storage. Returns `null` while storage is still
loading (in non-Suspense version).
### useHistory [@badge=RoomProvider]
Returns the room’s history. See [`Room.history`][] for more information.
```ts
import { useHistory } from "@liveblocks/react/suspense";
const { undo, redo, pause, resume } = useHistory();
```
_None_
The room's history object containing methods for undo, redo, pause, and
resume operations.
### useUndo [@badge=RoomProvider]
Returns a function that undoes the last operation executed by the current
client. It does not impact operations made by other clients.
```ts
import { useUndo } from "@liveblocks/react/suspense";
const undo = useUndo();
```
_None_
A function that undoes the last operation executed by the current client.
### useRedo [@badge=RoomProvider]
Returns a function that redoes the last operation executed by the current
client. It does not impact operations made by other clients.
```ts
import { useRedo } from "@liveblocks/react/suspense";
const redo = useRedo();
```
_None_
A function that redoes the last operation executed by the current client.
### useCanUndo [@badge=RoomProvider]
Returns whether there are any operations to undo.
```ts
import { useCanUndo, useUpdateMyPresence } from "@liveblocks/react/suspense";
const updateMyPresence = useUpdateMyPresence();
const canUndo = useCanUndo();
updateMyPresence({ y: 0 });
// At the next render, "canUndo" will be true
```
_None_
Whether there are any operations to undo.
### useCanRedo [@badge=RoomProvider]
Returns whether there are any operations to redo.
```ts
import {
useCanRedo,
useUndo,
useUpdateMyPresence,
} from "@liveblocks/react/suspense";
const updateMyPresence = useUpdateMyPresence();
const undo = useUndo();
const canRedo = useCanRedo();
updateMyPresence({ y: 0 });
undo();
// At the next render, "canRedo" will be true
```
_None_
Whether there are any operations to redo.
### useMutation [@badge=RoomProvider]
Creates a callback function that lets you mutate Liveblocks state.
```tsx
import { useMutation } from "@liveblocks/react/suspense";
const fillWithRed = useMutation(
// Mutation context is passed as the first argument
({ storage, setMyPresence }) => {
// Mutate Storage
storage.get("shapes").get("circle1").set("fill", "red");
// ^^^
// ...or Presence
setMyPresence({ lastUsedColor: "red" });
},
[]
);
// JSX
return ;
```
To make the example above more flexible and work with _any_ color, you have two
options:
1. Close over a local variable and
[adding it to the dependency array](#useMutation-dep-arrays), or
2. Have it take [an extra callback parameter](#useMutation-extra-params).
Both are equally fine, just a matter of preference.
A function that performs mutations on Liveblocks state. The context provides
access to `storage`, `setMyPresence`, `self`, and `others`.
A dependency array that determines when the mutation function should be
recreated, similar to `useCallback`.
#### With dependency arrays [#useMutation-dep-arrays]
```tsx
// Local state maintained outside Liveblocks
const [currentColor, setCurrentColor] = useState("red");
const fillWithCurrentColor = useMutation(
({ storage, setMyPresence }) => {
storage.get("shapes").get("circle1").set("fill", currentColor);
setMyPresence({ lastUsedColor: currentColor });
},
// +++
[currentColor] // Works just like it would in useCallback
// +++
);
// JSX
return ;
```
If you use ESLint, we recommend to
[configure it to enforce](/docs/api-reference/liveblocks-react#useMutation-lint-rule)
the correct use of your dependency arrays.
#### With extra callback parameters [#useMutation-extra-params]
Alternatively, you can add extra parameters to your callback function:
```tsx
const fill = useMutation(
// +++
// Note the second argument
({ storage, setMyPresence }, color: string) => {
// +++
storage.get("shapes").get("circle1").set("fill", color);
setMyPresence({ lastUsedColor: color });
},
[]
);
// JSX
// +++
return