Installation
Brook requires React 16.8.0 or later for hooks support.
Setup
Step 1: Initialize the Client
Create a Brook client instance outside your components:Step 2: Add the Provider
Wrap your app with theBrookProvider to make the client available to all components:
Step 3: Use the Hooks
Now you can use Brook hooks in any component within the provider:Hooks
useStream
Automatically subscribes to a topic and calls your callback function whenever a message is received.useStream automatically subscribes on component mount and unsubscribes on unmount. You typically don’t need to use the
subscribe and unsubscribe functions from the returned object - they’re only needed for manual control in advanced use cases.Usage
Parameters
Callback signature:
(message, metadata) => void
Returns
Example with State
useLazyStream
Subscribe to a topic on-demand (manual control over subscription).Usage
Parameters
Returns
Use Cases
- Toggle Subscription
- Conditional Subscription
usePublish
Publish messages to a topic.Usage
Parameters
Returns
Returns apublish function that accepts any serializable data.
publish(data)
Examples
- Simple Message
- Form Submission
- With Error Handling
useConnection
Monitor and control the connection status.Usage
Returns
Connection States
Examples
- Status Indicator
- Reconnection Handler
- Conditional Rendering
Complete Example
Here’s a complete chat application example:Best Practices
Message replay is automatic - when your app reconnects, you’ll receive any messages that were sent while offline.
Next Steps
JavaScript SDK
Learn about the underlying JavaScript SDK
REST API
Publish messages using REST API