useSubscribe
useSubscribe subscribes to a pub-sub topic for the lifetime of the component. The subscription is cleaned up automatically on unmount or when topic / enabled changes.
Usage
import { useSubscribe } from "@/components/realtime";
function PostNotifier() {
useSubscribe("resource/posts", (event) => {
console.log("post event", event.type, event.payload);
});
return null;
}Params
| Param | Required | Type | Description |
|---|---|---|---|
topic | Required | string | The topic to subscribe to |
callback | Required | (event: RealtimeEvent) => void | Called for each event on the topic |
options.enabled | Optional | boolean | Default true. Set to false to pause the subscription without unmounting |
Returns
void — the unsubscribe function is managed internally.
Notes
- The callback ref is updated on every render so you can safely use non-memoised callbacks without re-subscribing on every render.
- Throws if the
DataProviderin context does not implementsubscribe(). EnsurerealtimeDataProvider()is used to wrap your provider. - Use
options.enabledto conditionally subscribe based on runtime state (e.g. only subscribe when a record ID is known).