useEmitter
The useEmitter hook is your main tool for sending events to a server in React components. It integrates seamlessly
with Hyper Fetch's core systems, particularly the Emitter, to deliver a robust, reactive, and
efficient event-emitting experience.
- Declarative event emitting: Provide an
Emitterand let the hook manage the process. - Automatic connection management: Handles
connectedstate for you. - Lifecycle callbacks: Easily run side effects on events, errors, or reconnections.
- Deep core integration: Uses a central event dispatcher to send events.
If you intend to
listento events from the server, we recommend choosing theuseListenerhook.
Quick Start
To use useEmitter, provide a prepared Emitter instance. The hook returns an emit function
to send events and the current state of the socket connection.
First, let's define an emitter.
// src/api/chat.ts
import { socketInstance } from "./socket";
export const emitMessage = socketInstance.createEmitter<ChatMessageType, AcknowledgementResponseType>()({
endpoint: "chat-message", // endpoint of the event
});
Now, let's use it in a component.
// src/components/MessageComponent.tsx
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api/chat";
const MessageComponent: React.FC = () => {
const { emit, connected } = useEmitter(emitMessage);
const onSubmit = (values: { message: string }) => {
// ResponseDataType is automatically inherited from Emitter class
const acknowledge = (error: Error, data: ResponseDataType) => {
if (error) {
alert("No server response!");
} else {
alert("Message received on server.");
}
};
emit({ data: values }, acknowledge);
};
return (
<Form onSubmit={onSubmit}>
{/* ... form fields ... */}
<button type="submit" disabled={!connected}>
Send
</button>
</Form>
);
};
Event Handlers
To handle side effects such as notifications, logging, or triggering other actions, useEmitter provides a set of event
handler hooks. This keeps your component's rendering logic clean and separates side effects from state management.
onEmit: Fires before we send event message.onEmitError: Fires when an error occurs during the emission.onConnected: Fires when the socket connection is successfully opened.onDisconnected: Fires when the socket connection is closed.onConnecting: Fires when the socket is connecting.onReconnecting: Fires when the socket is attempting to reconnect.onReconnectingFailed: Fires when the socket fails to reconnect.
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api";
const MessageComponent: React.FC = () => {
const { emit, onEmit, onEmitError, onConnected, onDisconnected, onConnecting, onReconnecting, onReconnectingFailed } =
useEmitter(emitMessage);
onEmit((emitter) => {
// Event before we send event message
console.log(emitter); // Emitter instance
});
onEmitError((error) => {
console.log(error); // Error Event
});
onConnected(() => {
toast({ type: "info", message: "Socket connection opened." });
});
onDisconnected(() => {
toast({ type: "warning", message: "Socket connection closed." });
});
onConnecting(() => {
toast({ type: "info", message: "Socket is connecting." });
});
onReconnecting(({ attempts }) => {
toast({ type: "warning", message: `Reconnecting... (attempt ${attempts})` });
});
onReconnectingFailed(({ attempts }) => {
toast({ type: "error", message: `Reconnecting failed after ${attempts} attempts.` });
});
// ...
};
Sending Data
Data can be passed in several ways. One option is to use setData method on the Emitter.
const { emit } = useEmitter(emitMessage.setData({ message: "New message" }));
However, you may need to pass data dynamically, which requires using the emit function.
const { emit } = useEmitter(emitMessage);
const handleSubmit = (message: string) => {
// ResponseDataType is automatically inherited from Emitter class
emit({ data: { message } }, (error: Error, data: ResponseDataType) => {
if (error) {
alert("No server response!");
} else {
alert("Message received on server.");
}
});
};
Options
Customize the behavior of useEmitter by passing an options object as the second argument.
const { ... } = useEmitter(emitter, options)
| Name | Type | Description |
|---|---|---|
| dependencyTracking | |
Returns
useEmitter returns an object containing the socket's state and helper methods.
const values = useEmitter(emitter);
| Name | Type | Description |
|---|---|---|
| connected | | |
| connecting | | |
| clearState | | |
| emit | | |
| onConnected | | |
| onConnecting | | |
| onDisconnected | | |
| onEmit | | |
| onEmitError | | |
| onError | | |
| onReconnecting | | |
| onReconnectingFailed | | |
| setConnected | | |
| setConnecting | | |
| setData | | |
| setExtra | | |
| setTimestamp | |
