Add chat to your React app

Learn how to add LiveKit-powered chat functionality to your React app.

The useChat hook

LiveKit provides a simple abstraction on top of its Data Channels to help you incorporate chat into your web app.

Within a <LiveKitRoom> context, simply import our useChat React hook into your component:

import { useChat } from '@livekit/components-react'
export default function Chat() {
const { messages, send, isSending } = useChat();
...
}

useChat provides an object with 3 properties to manage your chat component:

  • messages - provides an array of ChatMessage objects that each have the properties:
    1. timestamp - when the message was sent
    2. from - information about the Participant who sent the message (e.g. identity)
    3. message - the message content provided as a JavaScript String
  • send - a function that takes a string input and takes care of publishing the message to all recipients in the Room
  • isSending - a boolean value that determines if the last message sent is currently in flight

A complete example

Livestream Example

Our livestream demo app is open-source and illustrates how you may want to add chat to your React application. It implements a standard chat UI using the above React hook and Tailwind for styling. You can take a look at the source here.

And in case you wanted an out-of-the-box experience

The LiveKit team has provided prefabricated UI components as part of the @livekit/components-react library. Included is the prefabricated <Chat> component that you can drop into your <LiveKitRoom> context. Ensure that you have installed the @livekit/components-styles library and write some code like below:

import { Chat } from "@livekit/components-react";
import '@livekit/components-styles';
export default function Room() {
return (
<LiveKitRoom data-lk-theme="default">
<Chat />
</LiveKitRoom>
)
}

To read more about styling our prefabricated components, refer to our documentation here.

Notes

  • Message history is not persisted and will be lost if the component is refreshed. You may want to persist message history in the browser, a cache or a database.