Getting started—React tutorial

//Broadcasting events

Broadcasting events

Another key feature of Liveblocks is the ability to broadcast custom events to other users. Events are ephemeral, and are sent to all users currently connected to the room, which makes them useful for:

  • Creating state controls, for example “next/previous slide” buttons in presentations
  • Letting other users know when to revalidate data after a change
  • Sending short-lived chat messages to other users

On this page, we’ll be using events to send toast notifications to other users.

Setting up types

The first step in broadcasting events is setting up your types. Let’s navigate to liveblocks.config.ts and create a RoomEvent type for our toasts. RoomEvent represents the object that will be broadcast to other users currently connected to the room. We’ll give it a type along with a message that can appear in the toast notification.

Modify the code in /liveblocks.config.ts
Multiple event types

If your app uses multiple event types, you can make RoomEvent a union type.

Broadcasting the events

Events can be broadcast to other users with the useBroadcastEvent hook. Switch to Room.tsx and add the hook, imported from our config file.

Modify the code in /Room.tsx

In the onClick event, pass an object to broadcast that matches the RoomEvent type specified above—this is how we send an event to other users.

Modify the code in /Room.tsx

Listening for events

We’re now sending an event, but we’re not listening for any. Import useEventListener and add it to the component. In the callback, we’re checking if the received event is a toast notification, and if it is, we’re calling a function that sends a toast notification with the message.

Modify the code in /Room.tsx

Try pressing the button to see other users receive toast notifications! You can also change the message and see an updated notification appear.