Getting started: Pub/Sub with React
This guide will get you started with Ably Pub/Sub in a new React application built with Vite.
You'll establish a realtime connection to Ably and learn to publish and subscribe to messages. You'll also implement presence to track other online clients, and learn how to retrieve message history.
Prerequisites
- Sign up for an Ably account.
- Create a new app, and create your first API key in the API Keys tab of the dashboard.
- Your API key will need the
publish,subscribe,presenceandhistorycapabilities.
Create a React project
Create a new React + TypeScript project using Vite. Then, navigate to the project folder and install the dependencies:
npm create vite@latest ably-pubsub-react -- --template react-ts
│
◇ Scaffolding project in /ably-pubsub-react...
│
└ Done. Now run:
cd ably-pubsub-react
npm installYou will also need to setup Tailwind CSS for styling the application. First, install the required Tailwind CSS packages:
npm install tailwindcss @tailwindcss/viteNext, update vite.config.ts file to include the Tailwind CSS plugin:
1
2
3
4
5
6
7
8
9
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
});Finally, import Tailwind CSS in the src/index.css file and remove all other existing CSS styles:
/* src/index.css */
@import 'tailwindcss';And replace the contents of src/App.tsx with the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/App.tsx
function App() {
return (
<div className='flex flex-col w-[900px] h-full border-1 border-blue-500 rounded-lg overflow-hidden mx-auto font-sans'>
<div className='flex flex-row w-full rounded-lg overflow-hidden mx-auto font-sans'>
<div className='flex-1 bg-gray-100 text-center p-4'>
<h2 className='text-lg font-semibold text-blue-500'>
Ably Pub/Sub React
</h2>
</div>
</div>
</div>
);
}
export default App;Install Ably Pub/Sub JavaScript SDK
Install the Ably Pub/Sub JavaScript SDK in your React project:
npm install @ably/pubsub-deviceSet up PubSubClientProvider
The Ably Pub/Sub SDK provides React hooks and context providers that make it easier to use Pub/Sub features in your React components.
The PubSubClientProvider component should be used at the top level of your application, typically in main.tsx. It provides access to the Ably Pub/Sub client for all child components that use Ably Pub/Sub React hooks.
Replace the contents of your src/main.tsx file with the following code to set up the PubSubClientProvider:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/main.tsx
import { createClient } from '@ably/pubsub-device';
import { PubSubClientProvider } from '@ably/pubsub-device/react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';
// Create your Ably Pub/Sub client
const pubsubDeviceClient = createClient({
key: 'demokey:*****',
clientId: 'my-first-client',
});
createRoot(document.getElementById('root')!).render(
<StrictMode>
<PubSubClientProvider client={pubsubDeviceClient}>
<App />
</PubSubClientProvider>
</StrictMode>
);(Optional) Install Ably CLI
Use the Ably CLI as an additional client to quickly test Pub/Sub features. It can simulate other clients by publishing messages, subscribing to channels, and managing presence states.
ably init installs the Ably CLI, authenticates, and sets the default app and API key in a single command:
npx @ably/cli initStep 1: Connect to Ably
Clients establish a connection with Ably when they instantiate an SDK instance. This enables them to send and receive messages in realtime across channels.
Open up the dev console of your first app before instantiating your client so that you can see what happens.
In the Set up PubSubClientProvider section, you added the following code to create an Ably Pub/Sub client:
1
2
3
4
const pubsubDeviceClient = createClient({
key: 'demokey:*****',
clientId: 'my-first-client',
});This code creates a new Pub/Sub client instance, establishing a connection to Ably when your application starts. At the minimum you need to provide an authentication mechanism. While using an API key is fine for the purposes of this guide, you should use token authentication in production environments. A clientId ensures the client is identified, which is required to use certain features, such as presence.
To monitor the Ably connection state within your application, create a component that uses the useConnectionStateListener() hook provided by the Ably Pub/Sub SDK. This hook must be nested inside a PubSubClientProvider, so the component must be placed within the PubSubClientProvider in your application.
In your project, create a new file src/ConnectionState.tsx with the following content:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/ConnectionState.tsx
// React hooks are exported from the '@ably/pubsub-device/react' path of the '@ably/pubsub-device' package.
import { usePubSubClient, useConnectionStateListener } from '@ably/pubsub-device/react';
import { useState } from 'react';
export function ConnectionState() {
// This component displays the current connection state
// The usePubSubClient hook returns the Ably Pub/Sub client instance provided by the PubSubClientProvider
const client = usePubSubClient();
const [connectionState, setConnectionState] = useState(client.connection.state);
// useConnectionStateListener hook listens for changes in connection state
useConnectionStateListener((stateChange) => {
setConnectionState(stateChange.current);
});
return (
<div className='mt-4 text-center h-full'>
<p>Connection: {connectionState}!</p>
</div>
);
}Then, update your App component in the src/App.tsx file to include the ConnectionState component:
1
2
3
4
5
6
7
8
9
10
11
12
13