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

ParamRequiredTypeDescription
topicRequiredstringThe topic to subscribe to
callbackRequired(event: RealtimeEvent) => voidCalled for each event on the topic
options.enabledOptionalbooleanDefault 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 DataProvider in context does not implement subscribe(). Ensure realtimeDataProvider() is used to wrap your provider.
  • Use options.enabled to conditionally subscribe based on runtime state (e.g. only subscribe when a record ID is known).