useCounts

Learn how to use the useCounts hook to fetch notification counts in your React application

The useCounts hook provides a way to fetch various notification counts, including unread, unseen, and total counts. This hook is useful for displaying notification badges and indicators in your application.

Hook Parameters

PropTypeDefault
filters?
NotificationFilter[]
-
onSuccess?
(data: Count[]) => void
-
onError?
(error: NovuError) => void
-

Return Value

type Count = {
  count: number;
  filter: NotificationFilter;
};
 
type UseCountsResult = {
  counts?: Count[];
  error?: NovuError;
  isLoading: boolean;
  isFetching: boolean;
  refetch: () => Promise<void>;
};

Example Usage

Here's how to use the useCounts hook to fetch and display notification counts:

import { useCounts } from "@novu/react";
 
function BellButton() {
  const { counts } = useCounts({ filters: [{ read: false }] });
  const unreadCount = counts?.[0].count ?? 0;
 
  return (
    <button>
      <BellIcon />
      {unreadCount > 0 && <span className="badge">{unreadCount}</span>}
    </button>
  );
}

The counts are automatically updated in real-time when notifications are marked as read/unread or when new notifications arrive.

On this page