The useCounts hook is used to fetch the notification counts based on the provided filters. You can use this hook to fetch the total count of unread, archived notifications or any other custom count based on the filters you provide.

The hook listens for changes in notification counts and will automatically refetch the counts whenever they are updated, for example, when a new notification is received.

useCounts props

filters
NotificationFilter[]

Filters to be applied to notifications when calculating counts, allowing you to filter notifications based on workflow tags, read status, and archived status.

onSuccess
Function

Callback function that will be called when the notification counts are successfully fetched. In the callback argument, you will receive the fetched counts.

onError
Function

Callback function that will be called when there is an error fetching the notification counts. In the callback argument, you will receive the error object.

useCounts returns

counts
Count[] | undefined

An array of notification counts fetched by the hook. If there are no notification counts fetched yet, it will be undefined.

isLoading
boolean

A boolean value indicating the first fetch for notification counts is in-flight.

isFetching
boolean

A boolean value indicating whether the hook is fetching more notification counts.

error
NovuError | undefined

An error object that will be populated if there is an error fetching the notification counts.

refetch
Function

A function that can be called to refetch the notification counts.

Example usage

The below example demonstrates how to use the useCounts hook to fetch the unread notifications count.

import { useCounts } from '@novu/react/hooks';

const BellButton = () => {
  const { counts } = useCounts({ filters: [{ read: false }] });

  return (
    <button>
      <BellIcon>
      {counts && counts[0].count > 0 && <span>{counts[0].count}</span>}
    </button>
  );
};