usePublishSubscribe
Communication system based on PubSub pattern. Instantiate a topic and use the publish and subscribe functions to communicate.
Demo
INFO
The component has:
- A useState that receives an object, with _value property.
- A usePubSubModel that receives demo as topic and returns the subscribe function.
- A child component that use usePubSubModel to get publish function and renders an input text with an onChange handler that invoke the publish function with input value as param.
The main component subscribe a listener, that updates component state, to the topic demo inside an useEffect, in this way the listener subscription is done only once and when the component is unmounted, it executes the unsubscription. The subscription can be done outside useEffect also, what's important is that listener doesn't change when component rerenders (so it can be declared outside the component or with useCallback for example). In this case the unsubscription is executed from hook.
Loading demo…
Show source code
tsx
import { BaseSyntheticEvent, memo, useCallback, useEffect, useState } from "react";
import { usePublishSubscribe } from "../../../..";
const ChildComponent = memo(() => {
const [, publish] = usePublishSubscribe("demo");
const onChange = useCallback((e: BaseSyntheticEvent) => {
publish({ value: e.target.value })
}, [publish]);
return (
<input type="text" onChange={onChange} />
);
})
const UsePublishSubscribe = () => {
const [state, setState] = useState({ value: "" });
const [subscribe] = usePublishSubscribe<typeof state>("demo");
useEffect(() => {
const unsub = subscribe((obj?: { value: string }) => {
obj && setState(obj);
})
return () => {
unsub();
}
}, [subscribe]);
return <div>
<p>Value is: {state.value}</p>
<ChildComponent/>
</div>
}
UsePublishSubscribe.displayName = "UsePublishSubscribe";
export { UsePublishSubscribe };Types
UsePublishSubscribeResult
@templateT Type of the message payload exchanged on the topic.
Result tuple returned by usePublishSubscribe.
| Index | Type | Description |
|---|---|---|
[0] | (listener: (value?: T) => void \| Promise<void>) => () => void | subscribe — registers a listener for the topic. Returns an unsubscribe function; unsubscribes automatically on component unmount. |
[1] | (value?: T) => Promise<void> | publish — broadcasts value to all current subscribers of the topic. |
