useExternalNotifications

Manages and synchronizes system notifications across multiple contexts using a global external store.

Important

This hook uses a global localStorage store to synchronize notifications across different browser tabs/windows.

Caution

Native OS notifications require explicit permission. You must call requestPermission() and receive a 'granted' status before notify() can display a visual alert outside the browser.

Note

The global store persists data in localStorage. Ensure you manage the lifecycle of this data if your app handles a high volume of notifications to avoid hitting storage limits.

Installation

bash

Description

This hook utilizes useSyncExternalStore to maintain a consistent state of notifications across different browser tabs or components. It allows emitting notifications from outside the standard React lifecycle (e.g., WebSockets) and persists them in localStorage.

Return values

NameTypeDescription
isSupportedbooleanIndicates if the browser supports the Notification API.
notificationsNotificationPayload[]An array of all notifications stored in the global history.
notify(notification: Omit<NotificationPayload, 'createdAt'>) => voidFunction to trigger a new system notification and save it to the store.
permissionNotificationPermissionCurrent permission status ('granted', 'denied', or 'default').
requestPermission() => Promise<NotificationPermission>Triggers the browser prompt to request notification permissions.

Demo

This component is loading.

Source code

tsx