PubNub React SDK 3.0.2

Chat SDK

If you want to create a React chat app, you can use our Chat SDK, which relies on the JavaScript SDK, is written in TypeScript, and offers a set of chat-specific methods to manage users, channels, messages, typing indicators, quotes, mentions, threads, and many more.

PubNub's React framework allows you to use PubNub's JavaScript SDK features within a React application.

React SDK deprecation

The older PubNub React SDK v.1.3.1 has been deprecated.

Requirements

To use the PubNub React framework, you need:

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the React wrapper

PubNub's React framework isn't a complete SDK. Rather, it's a wrapper around PubNub's JavaScript SDK that exposes the JS functionality to React components. This means that in order to work with PubNub's React framework, you need to download and add the JavaScript SDK to your React app.

  1. First, set up your React project. For a quick single-page app, create-react-app is a good starting point:

    npx create-react-app react-sample-chat
  2. Add the PubNub JavaScript SDK and React framework packages to your project:

    cd react-sample-chat
    npm install --save pubnub pubnub-react

Configure PubNub

In the IDE of your choice, open your React app in a new project and add the following to the source/App.js file. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the Admin Portal.

import React, { useState, useEffect } from 'react';
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';

const pubnub = new PubNub({
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
uuid: 'myUniqueUUID'
});

function App() {
return (
<PubNubProvider client={pubnub}>
<Chat />
</PubNubProvider>
show all 17 lines

For more information, refer to the Configuration section of the SDK documentation.

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Copy the code below to configure your app such that when it receives an event of type message, it adds the message to the responsible component's state. The component then renders based on its current state and displays the message.

function Chat() {
const pubnub = usePubNub();
const [channels] = useState(['awesome-channel']);
const [messages, addMessage] = useState([]);
const [message, setMessage] = useState('');
const handleMessage = event => {
const message = event.message;
if (typeof message === 'string' || message.hasOwnProperty('text')) {
const text = message.text || message;
addMessage(messages => [...messages, text]);
}
};
useEffect(() => {
        const listenerParams = { message: handleMessage }
        pubnub.addListener(listenerParams);
show all 21 lines

For more information, refer to the Listeners section of the SDK documentation.

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

In this app, publishing a message is triggered when you click the Send Message button.

To subscribe, you send a subscribe() call.

const sendMessage = message => {
if (message) {
pubnub
.publish({ channel: channels[0], message })
.then(() => setMessage(''));
}
};

useEffect(() => {
        const listenerParams = { message: handleMessage }
        pubnub.addListener(listenerParams);
        pubnub.subscribe({ channels });        
return () => {
            pubnub.unsubscribe({ channels })
            pubnub.removeListener(listenerParams)
show all 17 lines

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Sending Messages.

Putting it all together

Your App.js file should now look similar to the following. Note that the following code also defines some UI for demonstration:

import React, { useState, useEffect } from 'react';
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';

const pubnub = new PubNub({
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
uuid: 'myUniqueUUID'
});

function App() {
return (
<PubNubProvider client={pubnub}>
<Chat />
</PubNubProvider>
show all 147 lines

Now, run your app to see if you did everything correctly. In you project directory, run the npm start command. You should now see the chat UI in your browser. Try sending a message!

Congratulations! You've just subscribed to a channel and sent your first message.

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • passes the PubNub connection config to the PubNubProvider component (context) which allows you to use PubNub's functionality inside of other components of that context
  • adds the message event listener
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need to send and receive messages with PubNub. There is no React-specific behavior in this part. For more information, refer to the Configuration section of the SDK documentation.

import React, { useState, useEffect } from 'react';
import PubNub from 'pubnub';
import { PubNubProvider, usePubNub } from 'pubnub-react';

const pubnub = new PubNub({
publishKey: 'myPublishKey',
subscribeKey: 'mySubscribeKey',
uuid: 'myUniqueUUID'
});

Passing PubNub to Context

Passing the PubNub client configuration is a crucial step in using PubNub in your React app. By doing this, you make sure that the PubNub's functionality is available to all components in the PubNubProvider context. In our case, there is a single component Chat that uses PubNub, but if you wanted to add a new component that calls the PubNub API, you would need to add it to the PubNub Provider context as well. In your Chat component, you use the usePubNub() React hook to assign it to the pubnub variable.

function App() {
return (
<PubNubProvider client={pubnub}>
<Chat />
</PubNubProvider>
);
}

function Chat() {
const pubnub = usePubNub();
{...}

For more information, refer to the PubNubProvider and usePubNub sections.

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added a single listener to your app: message. The message listener listens for incoming messages on a channel. When it receives a message, it adds the message to the state of the messages array. React then registers a change in the array's state and renders its updated state. This is why you see all the messages you've sent displayed in your app's UI.

function Chat() {
const pubnub = usePubNub();
const [channels] = useState(['awesome-channel']);
const [messages, addMessage] = useState([]);
const [message, setMessage] = useState('');
const handleMessage = event => {
const message = event.message;
if (typeof message === 'string' || message.hasOwnProperty('text')) {
const text = message.text || message;
addMessage(messages => [...messages, text]);
}
};
useEffect(() => {
        const listenerParams = { message: handleMessage }
        pubnub.addListener(listenerParams);
show all 21 lines

For more information, refer to the Listeners section of the SDK documentation.

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named awesome-channel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When you click Send Message or press Enter, the sendMessage function is triggered, effectively publishing the message to awesome-channel. Subscribing to the channel happens in the React's useEffect hook.

const sendMessage = message => {
if (message) {
pubnub
.publish({ channel: channels[0], message })
.then(() => setMessage(''));
}
};

useEffect(() => {
        const listenerParams = { message: handleMessage }
        pubnub.addListener(listenerParams);
        pubnub.subscribe({ channels });
return () => {
            pubnub.unsubscribe({ channels })
            pubnub.removeListener(listenerParams)
show all 56 lines

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Sending Messages.

Next steps

You have just learned how to use PubNub's React framework to send and receive messages. Next, take a look at the JS SDK's reference documentation, which covers PubNub API in more detail.

Last updated on