# useSocket()&#x20;

Within the `useSocket()` function, two functions are encapsulated.

1. `joinRoom()`
2. `subscribe()`

With `joinRoom()` we can create a room for chats, games etc.&#x20;

> The `subscribe()` function acts as an event listener, fetching backend events upon occurrence. This enables the frontend to seamlessly display updates, eliminating the need for a page refresh—a functionality commonly exemplified in real-time messaging scenarios.

### Frontend

```typescript
import { useSocket } from '@magicjs.dev/frontend';

const { subscribe, joinRoom } = useSocket();

React.useEffect(() => {
    const leave = joinRoom(`public/room`);
    return leave;
}, []);

React.useEffect(() => {
    const unsubscribe = subscribe(`refresh`, () => {
        // Function you want to call after emitting
        handleFetchLatestMessage();
    });
    return unsubscribe;
}, []);
```

This code establishes a WebSocket connection to the designated room <mark style="color:blue;">`(public/room)`</mark> and subscribes to a specific event <mark style="color:blue;">`(refresh)`</mark>. Upon the occurrence of this event, the <mark style="color:purple;">`handleFetchLatestMessage`</mark> function is invoked. To ensure proper cleanup, the component gracefully exits the room and unsubscribes from the event upon unmounting.

### Backend

```typescript
import { createBackendFunction, data, io, useFunctionContext } from "@magicjs.dev/backend";
export default createBackendFunction(async function (message) {
    try {
        const messageCollection = data("messages"); // Fetching db
        const context = useFunctionContext(this);
        const userId = context.currentUser._id;
        const userName = context.currentUser.name;
        const messageItem = await messageCollection.insertOne({
            senderId: userId,
            senderName: userName,
            message
        });
        io().to(`public/room`).emit(`refresh`);
        return messageItem;
    } 
}});
```

{% hint style="info" %}
Here `io().to(public/room).emit(refresh)` emits an event to the room '`public/room`' with the name '`refresh`' when the insertion of a new message into a MongoDB collection.
{% endhint %}

> [Click here to refer GitHub.](https://github.com/skyslit/magicjs.dev/blob/main/packages/frontend/src/index.tsx#L174)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://skyslit.gitbook.io/magicjs/api-references/frontend/usesocket.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
