Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

use-notification

aaronccasanova36MIT0.3.0TypeScript support: included

React hook wrapping the Web Notification API.

readme

use-notification

React hook wrapping the Web Notification API.

Usage

npm install use-notification
import { useNotification } from 'use-notification'

useNotification ReturnType

interface UseNotificationReturnType {
  /**
   * Represents the permission status for displaying web notifications on
   * the current origin.
   *
   * @example 'default' | 'denied' | 'granted'
   */
  permission: NotificationPermission | null
  /**
   * Any error thrown while initializing the Notification constructor.
   */
  error: Error | null
  /**
   * Requests permission to display web notifications.
   */
  requestPermission: () => Promise<void>
  /**
   * Triggers a web notification.
   *
   * Note: The function signature matches the web Notification constructor one
   * to one. See the MDN documentation for more information:
   * https://developer.mozilla.org/en-US/docs/Web/API/Notification
   */
  notify: (
    title: Notification['title'],
    options?: NotificationOptions,
  ) => Notification | null
}

Examples

Note: The API is intentionally minimal and unopinionated to ensure the hook is flexible enough to handle multiple use cases. The following examples demonstrate some common configurations.

Example: Simple Notification

DemoCode Sandbox

import { useNotification } from 'use-notification'

function App() {
  const { permission, error, requestPermission, notify } = useNotification()

  if (error) {
    return (
      <div>
        Notification Error:
        <pre>{error.message}</pre>
      </div>
    )
  }

  return (
    <div>
      {permission === 'default' && (
        <button onClick={requestPermission}>Enable Notifications</button>
      )}
      <button onClick={() => notify('Hi')}>Notify</button>
    </div>
  )
}