@ably-labs/react-hooks

中文文档
2.1.2发布于 2023/10/30ISCTypeScriptESM + CJS近 30 天下载 7703

[!IMPORTANT] > The release candidate of our 3.0 react hooks library is currently available as a module of ably-js, which includes major improvements such as using a context provider and providing APIs to react to connection errors and channel errors.

此软件包已被标记为弃用

This package has moved to `ably/react`, see https://github.com/ably/ably-js/blob/main/docs/react.md for instructions on how to use to the latest version

原始使用文档
文档目录6 节
  1. Installation
  2. Compatible React Versions
  3. Ably channels and API keys
  4. Usage
  5. useChannel
  6. usePresence

@ably-labs/react-hooks

[!IMPORTANT]
The release candidate of our 3.0 react hooks library is currently available as a module of ably-js, which includes major improvements such as using a context provider and providing APIs to react to connection errors and channel errors. Please see the new react hooks README for installation instructions and usage examples.

Use Ably in your React application using idiomatic, easy to use, React Hooks!

Using this package you can:

  • Interact with Ably channels using a react hook.
  • Send messages via Ably using the channel instances the hooks provide
  • Get notifications of user presence on channels
  • Send presence updates

The hooks provide a simplified syntax for interacting with Ably, and manage the lifecycle of the Ably SDK instances for you taking care to subscribe and unsubscribe to channels and events when your react components re-render.



Installation

The hooks ship as an ES6 module, so you can use the import syntax in your react code.

npm install --save @ably-labs/react-hooks

This works out of the box using create-react-app - and you can use the package immediately.

Compatible React Versions

The latest version of this package tracks the latest version of react.

React Version@ably-labs/react-hooks Version
>=17.0.21.1.8
>=18.1.02.0.x (current)

Ably channels and API keys

In order to use these hooks, you will need an Ably API key. If you are not already signed up, you can sign up now for a free Ably account. Once you have an Ably account:

  1. Log into your app dashboard.
  2. Under “Your apps”, click on “Manage app” for any app you wish to use for this tutorial, or create a new one with the “Create New App” button.
  3. Click on the “API Keys” tab.
  4. Copy the secret “API Key” value from your Root key, we will use this later when we build our app.

It is strongly recommended that you use Token Authentication, this will require server side code that is outside of the scope of this readme. In the examples below we use an API key directly in the markup, this is for *local development only and should not be used for production code and should not be committed to your repositories.


Usage

Once you've added the package using npm to your project, you can use the hooks in your react code.

Start by adding a reference to the hooks

import { configureAbly, useChannel } from "@ably-labs/react-hooks";

Then you need to use the configureAbly function to create an instance of the Ably JavaScript SDK.

configureAbly({ key: "your-ably-api-key", clientId: generateRandomId() });

configureAbly matches the method signature of the Ably SDK - and requires either a string or an AblyClientOptions. You can use this configuration object to setup your API keys, or tokenAuthentication as you normally would. If you want to use the usePresence hook, you'll need to explicitly provide a clientId.

Once you've done this, you can use the hooks in your code. The simplest example is as follows:

const [channel] = useChannel("your-channel-name", (message) => {
    console.log(message);
});

Every time a message is sent to your-channel-name it'll be logged to the console. You can do whatever you need to with those messages.


useChannel

The useChannel hook lets you subscribe to a channel and receive messages from it.

const [channel, ably] = useChannel("your-channel-name", (message) => {
    console.log(message);
});

Both the channel instance, and the Ably JavaScript SDK instance are returned from the useChannel call.

useChannel really shines when combined with a regular react useState hook - for example, you could keep a list of messages in your app state, and use the useChannel hook to subscribe to a channel, and update the state when new messages arrive.

const [messages, updateMessages] = useState([]);
const [channel] = useChannel("your-channel-name", (message) => {
    updateMessages((prev) => [...prev, message]);
});

// Convert the messages to list items to render in a react component
const messagePreviews = messages.map((msg, index) => <li key={index}>{msg.data.someProperty}</li>);

useChannel supports all of the parameter combinations of a regular call to channel.subscribe, so you can filter the messages you subscribe to by providing a message type to the useChannel function:

const [channel] = useChannel("your-channel-name", "test-message", (message) => {
    console.log(message); // Only logs messages sent using the `test-message` message type
});

The channel instance returned by useChannel can be used to send messages to the channel. It's just a regular Ably JavaScript SDK channel instance.

channel.publish("test-message", { text: "message text" });

Because we're returning the channel instance, and Ably SDK instance from our useChannel hook, you can subsequently use these to perform any operations you like on the channel.

For example, you could retrieve history like this:

const [channel] = useChannel("your-channel-name", (message) => {
    console.log(message);
});

const history = channel.history((err, result) => {
    var lastMessage = resultPage.items[0];
    console.log('Last message: ' + lastMessage.id + ' - ' + lastMessage.data);
});

It's also worth highlighting that the useChannel hook supports all of the additional parameters that the regular Ably SDK does as we're simply passing the call along. This means you can use features like rewind:

const [channel] = useChannel("[?rewind=100]your-channel-name", (message) => {
    // This call will rewind 100 messages
    console.log(message);
});

We support providing ChannelOptions to the useChannel hook:

const [channel] = useChannel({ channelName: "your-channel-name", options: { ... } }, (message) => {
    ...
});

We also support providing your own Realtime instance to useChannel, which may be useful if you need to have more than one Ably client on the same page:

import { useChannel, Realtime } from '@ably-labs/react-hooks'

const realtime = new Realtime(options);

useChannel({ channelName: "your-channel-name", realtime: realtime }, (message) => {
    ...
})

for any cases where channel options must be provided (e.g. setting up encryption cypher keys).


usePresence

The usePresence hook lets you subscribe to presence events on a channel - this will allow you to get notified when a user joins or leaves the channel.

Please note that fetching present members is executed as an effect, so it'll load in after your component renders for the first time.

const [presenceData, updateStatus] = usePresence("your-channel-name");

// Convert presence data to list items to render    
const peers = presenceData.map((msg, index) => <li key={index}>{msg.clientId}: {msg.data}</li>);

usePresence returns an array of presence messages - again each message is a regular Ably JavaScript SDK presenceMessage instance.

You can optionally provide a string when you usePresence to set an initial presence data string.

const [presenceData, updateStatus] = usePresence("your-channel-name", "initial state");

// The `updateStatus` function can be used to update the presence data for the current client
updateStatus("new status");

The new state will be sent to the channel, and any other clients subscribed to the channel will be notified of the change immediately.

If you don't want to use the presenceData returned from usePresence, you can configure a callback

const [_, updateStatus] = usePresence("your-channel-name", "initial state", (presenceUpdate) => {
    console.log(presenceUpdate);
});

usePresence supports objects, as well as strings

usePresence("your-channel-name", { foo: "bar" });

and if you're using TypeScript there are type hints to make sure that updates are of the same type as your initial constraint, or a provided generic type parameter:

const TypedUsePresenceComponent = () => {
    // In this example MyPresenceType will be checked - if omitted, the shape of the initial 
    // value will be used ...and if that's omitted, `any` will be the default.

    const [val] = usePresence<MyPresenceType>("testChannelName", { foo: "bar" });

    return (
        <div role='presence'>
            {JSON.stringify(val)}
        </div>
    );
}

interface MyPresenceType {
    foo: string;
}

PresenceData is a good way to store synchronised, per-client metadata, so types here are especially valuable.

We also support providing your own Realtime instance to usePresence, which may be useful if you need to have more than one Ably client on the same page:

import { useChannel, Realtime } from '@ably-labs/react-hooks'

const realtime = new Realtime(options);

usePresence({ channelName: "your-channel-name", realtime: realtime }, (presenceUpdate) => {
    ...
})

版本与发布记录

@ably-labs/react-hooks 共发布 25 个版本,首次发布于 2021/10/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.1.2latest2023/10/303 年前
3.0.0-canary.1canary2023/08/183 年前
3.0.0-canary.02023/08/183 年前
2.1.12023/04/123 年前
2.1.02023/02/013 年前
2.0.112022/11/243 年前

关于 @ably-labs/react-hooks 的常见问题

@ably-labs/react-hooks 是什么?

[!IMPORTANT] > The release candidate of our 3.0 react hooks library is currently available as a module of ably-js, which includes major improvements such as using a context provider and providing APIs to react to connection errors and channel errors.注意:该包已被作者标记为弃用——This package has moved to `ably/react`, see https://github.com/ably/ably-js/blob/main/docs/react.md for instructions on how to use to the latest version

如何安装 @ably-labs/react-hooks?

在项目目录运行 npm install @ably-labs/react-hooks,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18.1.0)、react-dom(>=18.1.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ably-labs/react-hooks 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ably-labs/react-hooks 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ably-labs/react-hooks 可以商用吗?

@ably-labs/react-hooks 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ably-labs/react-hooks 的下载量有多少?

根据 npm 官方下载统计,@ably-labs/react-hooks 在 2026/10/05 – 2026/11/03 这 30 天内被下载 7,703 次,日均约 257 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ably-labs/react-hooks 还在维护吗?

最新版本 2.1.2 发布于 2023/10/30(3 年前);至今共发布 25 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/10/16。作者已将其标记为弃用,新项目建议寻找替代方案。