Skip to content

hook sendevent

Paulo Gomes da Cruz Junior edited this page Jun 16, 2026 · 3 revisions

📢 useSendEvent Hook

Overview

useSendEvent is a custom React hook that provides a unified interface for sending and subscribing to global events within your application. It is built on top of a generic event handler system, allowing you to trigger notifications, alerts, or any cross-cutting event from both React and non-React environments. This hook is ideal for decoupling event producers and consumers, such as triggering notifications from service workers, background scripts, or anywhere in your app.

🧪 Usage Example

import useSendEvent from '@/hooks/useSendEvent';

function MyComponent() {
  const { sendEvent, subscribe, unsubscribe } = useSendEvent();

  useEffect(() => {
    const onInfo = (event) => {
      // Handle info event (e.g., show notification)
      console.log(event.title, event.description);
    };
    const unsubscribeInfo = subscribe('info', onInfo);
    return () => unsubscribeInfo();
  }, [subscribe]);

  const handleClick = () => {
    sendEvent({
      eventType: 'info',
      title: 'Hello!',
      description: 'This is a global info event.',
    });
  };

  return <button onClick={handleClick}>Send Info Event</button>;
}

API

const { sendEvent, subscribe, unsubscribe } = useSendEvent();

  • sendEvent(detail: GlobalEvent): void
    • Sends a global event. All listeners for the event type will be notified.
    • detail should include at least eventType, title, and description.
  • subscribe(eventType: EventType, listener: EventListener): () => void
    • Subscribes a listener to a specific event type (e.g., 'info', 'error').
    • Returns an unsubscribe function.
  • unsubscribe(eventType: EventType, listener: EventListener): void
    • Unsubscribes a listener from a specific event type.

Event Types

  • 'info' — Informational events
  • 'success' — Success events
  • 'warning' — Warning events
  • 'error' — Error events

Advanced

You can also send events from outside React (e.g., service worker registration) using the exported sendEvent utility:

import { sendEvent } from '@/hooks/useSendEvent/eventHandler';

sendEvent({
  eventType: 'success',
  title: 'Update Available',
  description: 'A new version is ready to use!'
});

Type Definitions

  • GlobalEvent: { eventType: EventType; title: string; description: string; timeout?: number; }
  • EventType: 'info' | 'success' | 'warning' | 'error'
  • EventListener: (event: GlobalEvent) => void

When to Use

  • To trigger notifications or global events from anywhere in your app, including non-React code.
  • To decouple event producers (like service workers) from consumers (like notification UIs).
  • For a scalable, maintainable event-driven architecture.

See also: useOfflineMode, NotificationProvider

Waste Plus Wiki

Home

Architecture

Codes

Decisions

Knowledge Base

Development

Changes

Clone this wiki locally