Skip to content

Better React Support #298

Description

@aidanm3341

Summary

Add React utilities to make the message broker library easier to use in React applications. Currently, using the message broker in React requires manual subscription management and doesn't work well with React's lifecycle and state management.

Problem

E.g. this is how you'd currently use the messagebroker in a react app:

function MyComponent() {
  const [messages, setMessages] = useState([]);
  const [broker] = useState(() => messagebroker<IChannels>());

  useEffect(() => {
    const subscription = broker.get('myChannel').subscribe(message => {
      setMessages(prev => [...prev, message]);
    });

    return () => subscription.unsubscribe(); // <- Easy to forget
  }, [broker]);

 return (
    <div>
      {messages.map(msg => <div key={msg.id}>{msg.data}</div>)}
      <button onClick={() => broker.create('myChannel').publish('Hello!')}>Send Message</button>
    </div>
  );
}

Proposed Solution

Create react hooks for working with the messagebroker which handle the state management and lifecycle of subscriptions for the user.

E.g.

function MyComponent() {
  const { messages, publish } = useMessageBroker<IChannels>('myChannel');

  return (
    <div>
      {messages.map(msg => <div key={msg.id}>{msg.data}</div>)}
      <button onClick={() => publish('Hello!')}>Send Message</button>
    </div>
  );
}

Benefits

  • Subscriptions cleaned up when components unmount
  • Messages automatically update UI
  • Full TypeScript support with channel contracts
  • Uses standard React hooks pattern
  • Much less code needed for common use cases

This would make the message broker much more React-friendly and reduce the barrier to adoption in React applications.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions