useEventBus

A React Hook that provides a simple event bus for your application.

Demo

Source
Child Component
I will catch all the event emitted by parent
A:
0
B:
0
C:
0

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const { on, once, off, emit, reset } = useEventBus(identifier, options)

Identifier

export type EventBusIdentifier = symbol | string | number

Options

export type UseEventBusOptions = {
  /**
   * Whether to automatically clean up the listener when the component is unmounted.
   *
   * @defaultValue true
   */
  autoCleanup?: boolean
}

Returns

export type UseEventBusReturns<T, P> = {
  /**
   * Subscribe to an event. When calling emit, the listeners will execute.
   *
   * @param listener watch listener.
   * @returns a stop function to remove the current callback.
   */
  on: (listener: EventBusListener<T, P>) => AnyFunc
  /**
   * Similar to `on`, but only fires once
   *
   * @param listener watch listener.
   * @returns a stop function to remove the current callback.
   */
  once: (listener: EventBusListener<T, P>) => AnyFunc
  /**
   * Emit an event, the corresponding event listeners will execute.
   *
   * @param event data sent.
   */
  emit: (event?: T, payload?: P) => void
  /**
   * Remove the corresponding listener.
   *
   * @param listener watch listener.
   */
  off: (listener: EventBusListener<T>) => void
  /**
   * Clear all events in global scope
   */
  reset(): void
  /**
   * Clear all listeners in the current component context
   */
  cleanup(): void
}