Skip to main content
Version: v7.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>()({
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>
);
};
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. onEvent: Fires before we send event message.
  2. onError: Fires when an error occurs.
  3. onReconnecting: Fires when the socket is attempting to reconnect.
import { useEmitter } from "@hyper-fetch/react";
import { emitMessage } from "./api";

const MessageComponent: React.FC = () => {
const { emit, onEvent, onError, onReconnecting } = useEmitter(emitMessage);

onEvent((emitter) => {
// Event before we send event message
console.log(emitter); // Emitter instance
});

onError((error) => {
console.log(error); // Error Event
});

onReconnecting((reconnectingAttempt) => {
console.log(reconnectingAttempt); // 1
});

// ...
};

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

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
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.