Skip to content

useTopic

Subscribes to a ROS topic for the lifetime of the calling component and re-renders on every incoming message. Automatically resubscribes whenever the topic name/type or other subscription options change, and unsubscribes on unmount.

tsx
import { useTopic } from "roshooks";

interface StringMsg {
  data: string;
}

const { message, topic } = useTopic<StringMsg>({
  name: "/chatter",
  messageType: "std_msgs/String",
});

Options

OptionTypeDefaultDescription
namestringThe topic name, e.g. "/chatter".
messageTypestringThe message type, e.g. "std_msgs/String".
compressionstring"none""png", "cbor", "cbor-raw", or "none".
throttle_ratenumber0Minimum time (ms) between messages.
queue_sizenumber100The bridge-side publish queue size.
latchbooleanfalseLatch the topic when publishing.
queue_lengthnumber0The bridge-side subscribe queue length.
reconnect_on_closebooleantrueAutomatically resubscribe on reconnection.
enabledbooleantrueSet to false to skip subscribing (e.g. while waiting on other state).

Returns

FieldTypeDescription
messageTMessage | nullThe latest message received, or null until the first one arrives (or when enabled is false).
topicTopic<TMessage> | nullThe underlying roslib.js Topic instance, or null while not subscribed.

Example

tsx
function ChatterLabel() {
  const { message } = useTopic<{ data: string }>({
    name: "/chatter",
    messageType: "std_msgs/String",
  });

  return <p>{message?.data ?? "(none)"}</p>;
}

Conditionally subscribing

tsx
const { message } = useTopic<StringMsg>({
  name: "/chatter",
  messageType: "std_msgs/String",
  enabled: isVisible,
});

See also usePublisher for publishing to a topic, and Global State with Jotai if you want a single shared subscription across many components instead of one per call site.

Released under the BSD-3 License.