The Pub/Sub (Publish/Subscribe) pattern provides a way for components to communicate with each other without direct coupling. This is particularly useful for cross-component communication in a React application.
Add your new topic in the constants/PubSubTopics.ts file. This file contains all the topics used in the application.
// constants/PubSubTopics.ts
export const TOPICS = {
// ...existing topics
MY_TOPIC: 'my_topic',
};To publish events to a topic:
import { usePubSub } from "contexts";
const { publish, TOPICS } = usePubSub();
publish(TOPICS.MY_TOPIC, data); // data = additional data to pass to the subscribersTo subscribe (listen) to the published events:
import { usePubSub } from "contexts";
const { subscribe, TOPICS } = usePubSub();
useEffect(() => {
const unsubscribe = subscribe(TOPICS.MY_TOPIC, (data) => {
// Subscriber logic here...
});
return unsubscribe; // Unsubscribe on component unmount
}, []);- Always unsubscribe from topics when components unmount
- Keep data payloads small and focused
- Add new topics to the PubSubTopics constant file for better organization
- Use meaningful topic names that describe the event