Skip to content

useEventEmitter

Creates a small event bus shared through hook subscriptions.

Creates a small event bus shared through hook subscriptions.

Import

import { useEventEmitter } from '@kamod-ch/hooks'

Live demo

Basic demo

Creates a small event bus shared through hook subscriptions.

Last event: nothing yet

import { useState } from 'preact/hooks'
import { useEventEmitter } from '@kamod-ch/hooks'

export default function UseEventEmitterDemo() {
  const emitter = useEventEmitter<string>()
  const [lastMessage, setLastMessage] = useState('nothing yet')
  emitter.useSubscription((value) => setLastMessage(value))

  return (
    <div>
      <p><strong>Last event:</strong> {lastMessage}</p>
      <div class="demo-actions">
        <button type="button" onClick={() => emitter.emit('build started')}>Emit build started</button>
        <button type="button" onClick={() => emitter.emit('build finished')}>Emit build finished</button>
      </div>
    </div>
  )
}

API

TypeScript signature
type Subscription<T> = (val: T) => void;
export declare class EventEmitter<T> {
    private subscriptions;
    emit: (val: T) => void;
    useSubscription: (callback: Subscription<T>) => void;
}
declare const useEventEmitter: <T = void>() => EventEmitter<T>;
export default useEventEmitter;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.