Providers and Hooks
This page documents the providers and hooks available in the Ably Chat React UI Kit. These providers and hooks are used to manage state and provide functionality to the components.
Provider Setup
The components in the Ably Chat React UI Kit rely on several React context providers to provide necessary state and context. The ChatClientProvider is the core provider that manages access to the Ably Chat client, and should be placed at the root of your application.
Other providers like the ChatSettingsProvider, ThemeProvider and AvatarProvider can be used to manage themes, avatars, and chat settings respectively. These providers should be placed at the highest level of any component tree that contains Chat UI components.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
import { ChatClientProvider } from '@ably/chat/react';
import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit';
// Create Ably Realtime client
const ablyClient = new Ably.Realtime({
  key: 'demokey:*****', // Replace with your Ably API key
  clientId: 'your-chat-client-id',
});
const chatClient = new ChatClient(ablyClient);
function App() {
  return (
    <ChatClientProvider client={chatClient}>
      <ChatSettingsProvider>
        <ThemeProvider>
          <AvatarProvider>
            {/* Your Chat UI components */}
          </AvatarProvider>
        </ThemeProvider>
      </ChatSettingsProvider>
    </ChatClientProvider>
  );
}ChatSettingsProvider
The ChatSettingsProvider manages global and room-level chat settings across the application.
Features
- Provides default settings for message edits, deletes, and reactions
- Allows overriding settings globally or per room
- Provides a method to get effective settings for a room by merging global and room-specific settings
Props
| Prop | Description | 
|---|---|
| children | Child components that will have access to chat settings | 
| initialGlobalSettings | Initial global settings (merged with defaults) | 
| initialRoomSettings | Initial room-specific settings mapping | 
ChatSettings
| Setting | Description | 
|---|---|
| allowMessageUpdatesOwn | Whether users can update their messages after sending | 
| allowMessageUpdatesAny | Whether users can update any message in the room | 
| allowMessageDeletesOwn | Whether users can delete their messages | 
| allowMessageDeletesAny | Whether users can delete any message in the room | 
| allowMessageReactions | Whether users can add reactions to messages | 
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ChatSettingsProvider } from '@ably/chat-react-ui-kit';
const globalSettings = {
  allowMessageUpdatesOwn: false,
  allowMessageDeletesOwn: true,
  allowMessageReactions: true,
};
const roomSettings = {
  'general': { allowMessageUpdatesOwn: true },
  'announcements': {
    allowMessageUpdates: false,
    allowMessageDeletes: false,
  },
};
  <ChatSettingsProvider
    initialGlobalSettings={globalSettings}
    initialRoomSettings={roomSettings}>
    <ChatApp />
  </ChatSettingsProvider>;useChatSettings Hook
The useChatSettings hook provides access to the chat settings context.
Returns
| Property | Description | 
|---|---|
| globalSettings | Global settings that apply to all rooms | 
| roomSettings | Room-specific settings mapping | 
| getEffectiveSettings | Function to get effective settings for a room | 
Example
1
2
3
4
5
6
7
8
9
10
import { useChatSettings } from '@ably/chat-react-ui-kit';
const { getEffectiveSettings } = useChatSettings();
// Get settings for a specific room
const roomSettings = getEffectiveSettings('general');
// Check if message editing is allowed in this room
if (roomSettings.allowMessageUpdates) {
  // Show edit button
}ThemeProvider
The ThemeProvider manages theme state, persistence, and system theme integration across the application. All the components have pre-defined styles that adapt to the current theme.
Features
- Light/dark theme management with type safety
- Persistent theme preference in localStorage
- System theme preference detection and integration
- Change notifications for theme updates
- Performance optimizations with memoization
- Accessibility support with proper DOM updates
Props
| Prop | Description | 
|---|---|
| children | Child components that will have access to the theme context | 
| options | Configuration options for theme management | 
| onThemeChange | Callback fired when the theme changes | 
ThemeOptions
| Option | Description | 
|---|---|
| persist | Whether to persist theme preference to localStorage | 
| detectSystemTheme | Whether to detect and use system theme preference | 
| defaultTheme | Initial theme to use if no preference is found (light/dark) | 
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
import { ThemeProvider } from '@ably/chat-react-ui-kit';
<ThemeProvider
  options={{
    persist: true,
    detectSystemTheme: true,
    defaultTheme: 'dark'
  }}
  onThemeChange={(theme, prev) => {
    console.log(`Theme changed from ${prev} to ${theme}`);
  }}
>
  <ChatApplication />
</ThemeProvider>useTheme Hook
The useTheme hook provides access to the theme context for theme management. It allows you to get the current theme, set a new theme, toggle between themes, and register callbacks for theme changes.
Returns
| Property | Description | 
|---|---|
| theme | Current theme (light/dark) | 
| setTheme | Function to set the theme | 
| toggleTheme | Function to toggle between light and dark themes | 
| isDark | Whether the current theme is dark | 
| isLight | Whether the current theme is light | 
| supportsSystemTheme | Whether the browser supports system theme detection | 
| getSystemTheme | Function to get the current system theme | 
| resetToSystemTheme | Function to reset to the system theme | 
| onThemeChange | Function to register a theme change callback | 
Examples
1
2
3
4
5
6
7
8
9
10
11
12
// Basic theme usage
import { useTheme } from '@ably/chat-react-ui-kit';
const { theme, toggleTheme } = useTheme();
return (
  <button
    onClick={toggleTheme}
    className={theme === 'dark' ? 'bg-gray-800' : 'bg-white'}
  >
    Switch to {theme === 'dark' ? 'Light' : 'Dark'} Mode
  </button>
);1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Using boolean helpers
import { useTheme } from '@ably/chat-react-ui-kit';
const { isDark, setTheme } = useTheme();
return (
  <div className={isDark ? 'dark-mode' : 'light-mode'}>
    <button onClick={() => setTheme('light')}>
      Light Mode
    </button>
    <button onClick={() => setTheme('dark')}>
      Dark Mode
    </button>
  </div>
);1
2
3
4
5
6
7
8
9
10
11
12
13
// System theme integration
import { useTheme } from '@ably/chat-react-ui-kit';
const { supportsSystemTheme, getSystemTheme, resetToSystemTheme } = useTheme();
return (
  <div>
    {supportsSystemTheme && (
      <button onClick={resetToSystemTheme}>
        Use System Theme ({getSystemTheme()})
      </button>
    )}
  </div>
);1
2
3
4
5
6
7
8
9
10
11
12
13
// Theme change notifications
import { useEffect } from 'react';
import { useTheme } from '@ably/chat-react-ui-kit';
const { onThemeChange } = useTheme();
useEffect(() => {
  const cleanup = onThemeChange((newTheme, previousTheme) => {
    console.log(`Theme changed from ${previousTheme} to ${newTheme}`);
    // Update analytics, save preferences, etc.
  });
  return cleanup;
}, [onThemeChange]);AvatarProvider
The AvatarProvider manages avatar data for users and rooms across the application. It provides methods to generate, cache, and persist avatars, as well as handle avatar changes.
Features
- Generates and caches avatars for users and rooms
- Persists avatars to localStorage
- Provides methods to get, set, and update avatars
- Supports custom color palettes
- Handles caching and cache size limits
- Provides callbacks for avatar change events
Props
| Prop | Description | 
|---|---|
| children | Child components that will have access to the avatar context | 
| options | Configuration options for avatar management | 
AvatarOptions
| Option | Description | 
|---|---|
| persist | Whether to persist avatars to localStorage | 
| customColors | Custom color palette for avatar generation | 
| maxCacheSize | Maximum number of cached avatars (0 = unlimited) | 
| onError | Error handler callback | 
Example
1
2
3
4
5
6
7
8
9
10
11
import { AvatarProvider } from '@ably/chat-react-ui-kit';
<AvatarProvider
  options={{
    persist: true,
    customColors: ['bg-blue-500', 'bg-red-500', 'bg-green-500'],
    maxCacheSize: 50,
    onError: (error) => console.error('Avatar error:', error),
  }}
>
  <ChatApplication />
</AvatarProvider>;useAvatar Hook
The useAvatar hook provides access to the avatar context with comprehensive avatar management.
Returns
| Property | Description | 
|---|---|
| getAvatarForUser | Get avatar for a user | 
| getAvatarForRoom | Get avatar for a room | 
| setUserAvatar | Set avatar for a user | 
| setRoomAvatar | Set avatar for a room | 
| resetUserAvatar | Reset avatar for a user | 
| resetRoomAvatar | Reset avatar for a room | 
| exportAvatars | Export all avatars as a JSON string | 
| importAvatars | Import avatars from a JSON string | 
| onAvatarChange | Register an avatar change callback | 
Examples
You can use the useAvatar hook to manage user and room avatars in your chat application:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { useState, useCallback } from 'react';
import { useAvatar } from '@ably/chat-react-ui-kit';
// Basic usage
function UserAvatar({ clientId, displayName }) {
  const { getAvatarForUser } = useAvatar();
  const avatar = getAvatarForUser(clientId, displayName);
  return (
    <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-medium ${avatar.color}`}>
      {avatar.src ? (
        <img
          src={avatar.src}
          alt={displayName}
          className="w-full h-full rounded-full object-cover"
        />
      ) : (
        avatar.initials
      )}
    </div>
  );
}
// Setting a user avatar
function UserAvatarManager() {
  const { getAvatarForUser, setUserAvatar } = useAvatar();
  const [userId] = useState('user-123');
  const [displayName] = useState('John Doe');
  const avatar = getAvatarForUser(userId, displayName);
  const handleAddUser = useCallback(() => {
    // When adding a new user, set their avatar with custom properties
    setUserAvatar(userId, {
      color: 'bg-blue-500',
      initials: 'JD',
      src: 'https://example.com/avatar.jpg'
    });
  }, [setUserAvatar, userId]);
  return (
    <div className="p-4 space-y-4">
      <div className="flex items-center gap-4">
        <div className={`w-16 h-16 rounded-full flex items-center justify-center text-white font-medium ${avatar.color}`}>
          {avatar.src ? (
            <img src={avatar.src} alt={displayName} className="w-full h-full rounded-full object-cover" />
          ) : (
            avatar.initials
          )}
        </div>
        <div>
          <div className="font-medium">{displayName}</div>
          <div className="text-sm text-gray-500">User ID: {userId}</div>
        </div>
      </div>
      <div className="flex gap-2">
        <button
          onClick={handleAddUser}
          className="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600"
        >
          Add User
        </button>
      </div>
    </div>
  );
}You can also use the useAvatar hook to manage avatars for rooms, reset avatars, and handle avatar changes:
1
2
3
4
5
6
7
8
9
10
11
12
import { useEffect } from 'react';
import { useAvatar } from '@ably/chat-react-ui-kit';
// Listen for avatar changes
const { onAvatarChange } = useAvatar();
useEffect(() => {
  const cleanup = onAvatarChange((type, id, avatar, prev) => {
    console.log(`${type} avatar changed for ${id}`);
  });
  return cleanup;
}, [onAvatarChange]);1
2
3
4
5
6
7
8
9
import { useAvatar } from '@ably/chat-react-ui-kit';
// Backup and restore avatars
const { exportAvatars, importAvatars } = useAvatar();
// Backup all avatars
const backup = exportAvatars();
// Restore from backup
importAvatars(backup);useUserAvatar Hook
The useUserAvatar hook provides a simplified way to manage avatar data for a specific user. On render, it automatically retrieves the current avatar data for the user and provides a function to update it.
If no avatar data exists, it will generate a default avatar based on the user's client ID and display name. Avatar data is stored in a useState, and updates are automatically reflected in the UI.
Props
| Prop | Description | 
|---|---|
| clientId | The unique identifier for the user | 
| displayName | Optional human-readable display name for the user | 
Returns
| Property | Description | 
|---|---|
| userAvatar | The current state of avatar data for the user, kept up-to-date automatically | 
| setUserAvatar | Function to update the user avatar with new data | 
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useUserAvatar } from '@ably/chat-react-ui-kit';
// Basic usage
function UserProfile({ userId, name }) {
  const { userAvatar, setUserAvatar } = useUserAvatar({
    clientId: userId,
    displayName: name
  });
  return (
    <div className="flex items-center gap-3">
      <Avatar
        src={userAvatar?.src}
        color={userAvatar?.color}
        initials={userAvatar?.initials}
        alt={userAvatar?.displayName}
      />
      <div>
        <h3>{userAvatar?.displayName}</h3>
        <button
          onClick={() => setUserAvatar({
            color: 'bg-blue-500',
            src: 'https://example.com/new-avatar.jpg'
          })}
        >
          Update Avatar
        </button>
      </div>
    </div>
  );
}useRoomAvatar Hook
The useRoomAvatar hook provides a simplified way to manage avatar data for a specific room. On render, it automatically retrieves the current avatar data for the room and provides a function to update it.
If no avatar data exists, it will generate a default avatar based on the room name and display name. Avatar data is stored in a useState, and updates are automatically reflected in the UI.
Props
| Prop | Description | 
|---|---|
| roomName | The unique identifier for the room | 
| displayName | Optional human-readable display name for the room | 
Returns
| Property | Description | 
|---|---|
| roomAvatar | The current avatar data for the room | 
| setRoomAvatar | Function to update the room avatar with new data | 
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { useRoomAvatar } from '@ably/chat-react-ui-kit';
// Basic usage
function RoomHeader({ roomId, roomTitle }) {
  const { roomAvatar, setRoomAvatar } = useRoomAvatar({
    roomName: roomId,
    displayName: roomTitle
  });
  return (
    <div className="flex items-center gap-3">
      <Avatar
        src={roomAvatar?.src}
        color={roomAvatar?.color}
        initials={roomAvatar?.initials}
        alt={roomAvatar?.displayName}
      />
      <h2>{roomAvatar?.displayName}</h2>
      <button
        onClick={() => setRoomAvatar({
          displayName: 'Updated Room Name',
          color: 'bg-green-500'
        })}
      >
        Edit Room
      </button>
    </div>
  );
}