Skip to content

useNotifications

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useNotifications

Requests browser notification permission and sends local OS notifications. It integrates securely with the browser's Notification API.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation. By default, it will automatically ask the user for notification permissions when mounted.

import { useNotifications } from 'react-hook-lab';

function BasicNotifier() {
  const { sendNotification, permission } = useNotifications();

  return (
    <button 
      onClick={() => sendNotification("Hello from React Hook Lab!")}
      disabled={permission !== 'granted'}
    >
      Send Alert
    </button>
  );
}

Common (Standard Usage)

Disabling the automatic permission request so that the user is only prompted when they click a button.

import { useNotifications } from 'react-hook-lab';

function SafeNotifier() {
  // autoRequest: false ensures we don't spam the user on mount
  const { permission, requestPermission, sendNotification } = useNotifications({ autoRequest: false });

  const handleNotify = () => {
    if (permission === 'granted') {
      sendNotification("Download Complete!", { body: "Your file is ready." });
    } else if (permission === 'default') {
      requestPermission();
    }
  };

  return (
    <button onClick={handleNotify}>
      {permission === 'default' ? 'Enable Notifications' : 'Notify Me'}
    </button>
  );
}

Advanced (All Parameters)

An exhaustive example utilizing errors, tracking specific notification references, and closing them automatically.

import { useNotifications } from 'react-hook-lab';

function AdvancedNotifier() {
  const { permission, error, sendNotification, closeAllNotifications, isSupported } = useNotifications({ autoRequest: false });

  if (!isSupported) return <p>Your browser doesn't support notifications.</p>;

  const triggerSelfDestructingNotification = () => {
    // The native NotificationOptions object accepts icons, badges, etc.
    const notif = sendNotification("Temporary Alert", {
      body: "This will disappear in 3 seconds",
      icon: "/favicon.ico"
    });

    if (notif) {
      setTimeout(() => notif.close(), 3000);
    }
  };

  return (
    <div>
      <button onClick={triggerSelfDestructingNotification}>Send 3s Notification</button>
      <button onClick={closeAllNotifications}>Force Close All Active</button>
      {error && <p style={{color: 'red'}}>Error: {error}</p>}
      <p>Permission Status: <strong>{permission}</strong></p>
    </div>
  );
}

API Reference

Parameters

  • options
    • Type: UseNotificationsOptions
    • Default: { autoRequest: true }
    • Description: Configuration object.
      • autoRequest: (boolean) If true, automatically prompts for notification permission on component mount if the current permission is "default". Note: Many modern browsers block automatic requests without a user gesture, so false is often safer.

Return Object

Returns UseNotificationsReturn:

  • permission (NotificationPermissionStatus): The current state of permissions. Can be "granted", "denied", "default", or "unsupported".
  • isSupported (boolean): True if the browser supports the Notification API.
  • error (string | null): The error message if a notification fails to send or permissions are denied.
  • requestPermission (() => Promise<NotificationPermissionStatus>): Prompts the user for permission.
  • sendNotification ((title: string, options?: NotificationOptions) => Notification | null): Triggers a system notification. Returns the native Notification instance, or null if it failed.
  • closeAllNotifications (() => void): Instantly closes all active notifications sent by this hook instance.
  • recheckPermission (() => NotificationPermissionStatus): Manually re-evaluates the browser's permission state (useful if the user changed settings externally).

Clone this wiki locally