Skip to main content
Version: 5.x.x

useListener


Introduction

This hook is created to listen to events received from the server.

If you intend to send events to the server, we recommend choosing the useEmitter hook.


Initialization

const { data, timestamp, connected, connecting, onEvent, onError, onReconnecting } = useListener(onChatMessage);

How it works?

useListener hooks into Socket adapter and start listening to given event when a component is mounted. It uses dependency tracking to limit re-rendering and help with performance.

Under the hood, communication with the core systems is established by event emitters. There are many "helper hooks" that get returned from the hook, like onEvent, onError, and onReconnecting (among others). They will help you handle various events in the lifecycle of sockets communication.

We used this approach to avoid overloading the base hook with callback logic, which causes low code readability and increases complexity.

import { socketInstance } from "./socket";

export const onChatMessage = socketInstance.createListener<ChatMessageType>()({
endpoint: "chat-message", // endpoint of the event
});

Use it in your component.

import { useListener } from "@hyper-fetch/react";
import { onChatMessage } from "server";

const UsersListPage: React.FC = () => {
const [messages, setMessages] = useState([])
const { data, connected, connecting, onEvent, onError, onReconnecting } = useListener(onChatMessage);

onEvent(({ data: message }) => {
setMessages((prev) => [...prev, message]); // [ MessageType, MessageType, MessageType ]
});

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

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

if(error && !connecting) {
return <Alert severity="error">{error.message}</Alert>
}

return (
<div>
{connecting && <Loader>}
{!messages.length && <div>No messages</div>}
{!messages.length && <div>{messages.map(message => <div>{message}</div>)}</div>}
</div>
);
};

Options

Configuration options for useListener must be provided as the second parameter.

const { ... } = useListener(listener, options)

{
dependencyTracking: boolean;
}


Returns

Returned values from this hook.

const values = useListener(listener);

{
connected: boolean;
connecting: boolean;
data: unknown;
listen: () => void;
onClose: (callback: VoidFunction) => void;
onConnecting: (callback: VoidFunction) => void;
onError: (callback: (event: ErrorType) => void) => void;
onEvent: (callback: (response: [object Object]) => void) => void;
onOpen: (callback: VoidFunction) => void;
onReconnecting: (callback: (attempts: number) => void) => void;
onReconnectingStop: (callback: (attempts: number) => void) => void;
setConnected: (connected: boolean) => void;
setConnecting: (connecting: boolean) => void;
setData: (data: unknown) => void;
setTimestamp: (timestamp: number) => void;
timestamp: number;
}