There are multiple places you could handle your Ably channel subscriptions

1. In a component that reacts to Ably messages.

2. Somewhere globally in the app, that then passes messages onwards via state management, props, or some other mechanism.

An example component can be seen below or in this gist:

import React from 'react'
import Ably from "ably/promises";

const client = new Ably.Realtime("your-ably-api-key");

export default class AblyMessageComponent extends React.Component {
  constructor() {
    this.state = { messages: [] };

  async componentDidMount() { = await client.channels.get("my-cool-channel");
    await => {
      console.log("A message was received", message);

      this.setState({ messages: this.state.messages });

    console.log("You are subscribed");

  async componentWillUnmount() {;

    console.log("You are unsubscribed");
  sendMessage() {{ name: "myEventName", data: { text: "Some random stuff here." } })

  render() {
    return (
        <button onClick={ (e) => this.sendMessage(e) }>Click here to send a message</button>
        <h2>Messages will appear here:</h2>
          {, index) => (<li key={"item" + index}>{text}</li>))}

  • The Ably client is created outside of the scope of the component and used inside of it.
  • State is set up in the constructor
  • Get the Ably channel in the componentDidMount() function.
  • Subscribe in componentDidMount()
  • Make sure to unsubscribe in componentWillUnmount()
  • Click handler on a button will publish new messages

Why this specific setup is important:

The Ably channel needs to remain connected while the component is visible and mounted in your application. By creating channel subscriptions during componentDidMount()you make sure that the Ably client connects and disconnects appropriately as the component is toggled on or off.

In addition - making sure that you unsubscribe during componentWillUnmount() prevents you from using up Ably connections against your connection limit, while your users cannot interact with the component.

If you need multiple components to react to Ably messages, you will need to manage this subscription and cascade the received messages in another way, probably from a parent component passing the received message data as props, or using your own state management solution.

Please note - the above example uses the Ably API key in the constructor call to Ably.Realtime. In a production scenario, you should use Token Authentication instead, as putting your Ably API key directly into your React JSX markup exposes your API key to theft and abuse.