Skip to main content
Version: v8.0.0

useEmitter

Read the API Reference »

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.

Purpose
  1. Declarative event emitting: Provide an Emitter and let the hook manage the process.
  2. Automatic connection management: Handles connected state for you.
  3. Lifecycle callbacks: Easily run side effects on events, errors, or reconnections.
  4. Deep core integration: Uses a central event dispatcher to send events.

If you intend to listen to events from the server, we recommend choosing the useListener hook.


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>()({
topic: "chat-message", // topic 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>
);
};
Emitter
Learn more about creating and configuring emitters.

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.

  1. onEmit: Fires before we send event message.
  2. onEmitError: Fires when an error occurs during the emission.
  3. onConnected: Fires when the socket connection is successfully opened.
  4. onDisconnected: Fires when the socket connection is closed.
  5. onConnecting: Fires when the socket is connecting.
  6. onReconnecting: Fires when the socket is attempting to reconnect.
  7. 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)

UseEmitterOptionsType
Name Type Description
dependencyTracking
boolean
When true (default), only re-renders when accessed state properties change

UseEmitterOptionsType API Reference
Learn more about the useEmitter hook options.

Returns​

useEmitter returns an object containing the socket's state and helper methods.

const values = useEmitter(emitter);

useEmitter
Name Type Description
connected
boolean
connecting
boolean
clearState
() => void
emit
EmitType<EmitterType>
onConnected
(callback: VoidFunction) => void
onConnecting
(callback: VoidFunction) => void
onDisconnected
(callback: VoidFunction) => void
onEmit
(callback: (emitter: EmitterType) => void) => void
onEmitError
(callback: EmitterCallbackErrorType) => void
onError
<ErrorType>(callback: (event: ErrorType) => void) => void
onReconnecting
(callback: (data: { attempts: number }) => void) => void
onReconnectingFailed
(callback: (data: { attempts: number }) => void) => void
setConnected
(connected: boolean) => void
setConnecting
(connecting: boolean) => void
setData
(data: unknown) => void
setExtra
(extra: any) => void
setTimestamp
(timestamp: null | number) => void

useEmitter API Reference
Learn more about the values returned from the useEmitter hook.

See More​

useListener
Learn more about the useListener hook for receiving socket events.
Emitter
Learn more about the Emitter class.
Socket
Learn more about creating a socket instance.