# Unread count in the tab title

The browser tab can show how many messages the user hasn't read, as "(3) My app", so the user sees new messages while another tab is in front. The SDK doesn't write the tab title, because what belongs there depends on your app. This recipe adds a component that writes it.

>
> **Note:** **What you'll build**
>
> - The user's unread message count in front of the tab title, across all channels
> - The plain title while nothing is unread
> - A count that stays right after the connection drops and comes back
>

**Approach:** Compose. [Choosing where to start](https://getstream.io/chat/docs/sdk/react/ui-cookbooks/overview/#choosing-where-to-start) explains the approaches.

**Starts from:** [the base app](https://getstream.io/chat/docs/sdk/react/ui-cookbooks/overview/#the-base-app). The page shows only what the recipe adds.

## When to use this pattern

- Your app runs in a browser tab, and users switch to other tabs while they wait for replies.

## Implementation

### 1. The title component

`<UnreadCountInTitle/>` renders nothing. It keeps `document.title` in step with one number: the user's unread messages across all channels, as the server counts them.

- **Where the count comes from.** The server sends the count as a `total_unread_count` field in two places:
- **The current user.** The `connection.ok` event that opens the connection carries the current user, which the client keeps as `client.user`. So `client.user.total_unread_count` holds the count as of the connection.
- **The events that change the count,** as `event.total_unread_count`: `message.new`, `notification.message_new`, `notification.mark_read` and `notification.mark_unread`, among others.

  The React component state is initiated from `client.user.total_unread_count` and takes the new value from each event that carries one.

- **After a reconnect.** Events sent while the connection was down never arrive. The `connection.ok` event of the new connection carries `event.me.total_unread_count`, the current count, so the title is right again as soon as the client is back online.
- **The title.** The `appTitle` prop is the title without a count. The component builds the title from it each time, and never from what `document.title` holds, so the count is never added twice.
- **On unmount.** The component writes `appTitle` back, so no count stays in the title.

```tsx title="src/UnreadCountInTitle.tsx"
import { useEffect, useState } from "react";
import type { Event } from "stream-chat";
import { useChatContext } from "stream-chat-react";

// The server's count of the user's unread messages across every channel. The events that change
// it carry it (`message.new`, `notification.mark_read`, `notification.mark_unread`, …), and the
// `connection.ok` event carries it again in `event.me` after every reconnect, so a count missed
// while offline is corrected.
const readTotalUnreadCount = (event: Event): number | undefined => {
  if (
    "total_unread_count" in event &&
    typeof event.total_unread_count === "number"
  ) {
    return event.total_unread_count;
  }
  return "me" in event ? event.me?.total_unread_count : undefined;
};

const useTotalUnreadCount = () => {
  const { client } = useChatContext();
  const [totalUnreadCount, setTotalUnreadCount] = useState(
    () => client.user?.total_unread_count ?? 0,
  );

  useEffect(() => {
    // The count as of the connection, for a component that mounts after it opened.
    setTotalUnreadCount(client.user?.total_unread_count ?? 0);

    const subscription = client.on((event) => {
      const count = readTotalUnreadCount(event);
      if (count !== undefined) setTotalUnreadCount(count);
    });

    return () => subscription.unsubscribe();
  }, [client]);

  return totalUnreadCount;
};

export type UnreadCountInTitleProps = {
  /** The page title without a count, for example the app's name. */
  appTitle: string;
};

/**
 * Puts the user's unread message count in front of the page title, as "(3) My app", and shows
 * the plain title while nothing is unread. Renders nothing; place it anywhere inside Chat.
 */
export const UnreadCountInTitle = ({ appTitle }: UnreadCountInTitleProps) => {
  const totalUnreadCount = useTotalUnreadCount();

  useEffect(() => {
    document.title =
      totalUnreadCount > 0 ? `(${totalUnreadCount}) ${appTitle}` : appTitle;
  }, [appTitle, totalUnreadCount]);

  // Leaves the plain title behind when this component unmounts.
  useEffect(
    () => () => {
      document.title = appTitle;
    },
    [appTitle],
  );

  return null;
};
```

### 2. Mount it inside Chat

The count belongs to the user, not to the open channel, so the component goes inside `<Chat/>`, outside any `<Channel/>`. It keeps counting while the user is in another channel or in the threads view:

```tsx title="src/App.tsx"
import type { PropsWithChildren } from "react";
import { Chat } from "stream-chat-react";
import { UnreadCountInTitle } from "./UnreadCountInTitle";

export const App = ({ children }: PropsWithChildren) => (
  <Chat client={client}>
    <UnreadCountInTitle appTitle="My app" />
    {children}
  </Chat>
);
```

## How it works

>
> **Info:** **Example**
>
> The user has two unread messages in the Book club channel, opens the app in a tab and switches to another tab:
>
> 1. The connection opens. `client.user.total_unread_count` is 2, and the tab reads "(2) My app".
> 2. Bob writes in the Design review channel. The `message.new` event (`notification.message_new` if the client doesn't watch that channel) carries `total_unread_count: 3`, and the tab reads "(3) My app".
> 3. The user comes back, opens Book club and scrolls to its newest message. `<MessageList/>` marks the channel read, the `notification.mark_read` event carries `total_unread_count: 1`, and the tab reads "(1) My app".
> 4. The user opens Design review and reads the new message. The `notification.mark_read` event carries `total_unread_count: 0`, and the tab reads "My app".
>

The total follows the server's rules, which leave out:

- **The user's own messages,** and silent and shadowed messages.
- **Thread replies that aren't shown in the channel.** The number of threads with unread replies is `client.threads.state.unreadThreadCount`. To show both, put them side by side, as "(3 · 1 thread) My app". Don't add them together: one counts messages, the other counts threads.
- **Channels whose channel type has `read_events` off,** set in the Stream Dashboard or through the server API. With `channel.readEvents.localUnreadCountEnabled` in `client.config`, such a channel counts its unread messages on the client, but they don't reach the total.

The rules for a single channel's own count, which the SDK keeps on the client, are in [Read state and unread counts](https://getstream.io/chat/docs/sdk/react/state/channels-and-threads/read-state-and-unread-counts/#what-counts-as-unread-in-a-channel).

## Related

- [Read state and unread counts](https://getstream.io/chat/docs/sdk/react/state/channels-and-threads/read-state-and-unread-counts/): what marks a channel read and what counts as unread.
- [Read state, unread and receipts](https://getstream.io/chat/docs/sdk/react/features/messaging/read-state-unread-and-receipts/): the unread UI the SDK renders.
- [Threads view](https://getstream.io/chat/docs/sdk/react/ui-cookbooks/panels/threads-view/): unread counts for threads.
- [Upgrade to v15](https://getstream.io/chat/docs/sdk/react/release-guides/upgrade-to-v15/#channel-no-longer-writes-documenttitle): what to change in an app that relied on `<Channel/>` for the title.

---

For the most recent version of this documentation, visit [https://getstream.io/chat/docs/sdk/react/ui-cookbooks/notifications/unread-count-in-tab-title/](https://getstream.io/chat/docs/sdk/react/ui-cookbooks/notifications/unread-count-in-tab-title/).