@jcmagoo/react-event-emitter

Hook based pub/sub event emitter for React Single Page Applications (SPA)

Usage no npm install needed!

<script type="module">
  import jcmagooReactEventEmitter from 'https://cdn.skypack.dev/@jcmagoo/react-event-emitter';
</script>

README

@magoo/react-event-emitter

React hook for event subscription and publishing

npm version Known Vulnerabilities CI Build Test Coverage

Contents

If you're creating a React hook, and need to provide a mechanism for client components to subscribe to events that the hook raises, then this module is for you!

Instalation

Using npm

npm install @jcmagoo/react-event-emitter

Using yarn

yarn add @jcmagoo/react-event-emitter

Getting Started

Here's a very simple example of subscribing to an emitter, and emitting an event.

import useEventEmitter from './src'

const {useSubscription, emit} = useEventEmitter()

useSubscription(() => console.log('Hello Foo!'))
useSubscription(() => console.log('Hello Bar'))

emit()

// Hello Foo
// Hello Bar

When used in a custom hook, typically the hook would expose the useSubscription method to allow consumers to register callbacks to be notified of events by the hook. The hook itself would call emit when it needed to trigger the notification.

API Reference

useEventEmitter

const {
    useSubscription,
    emit
} = useEventEmitter();

Use the useEventEmitter hook to add pub/sub event support to your components and hooks.

useSubscription

useSubscription(callback)

Add a subscription to the event emitter.

emit

emit()

Call the callback for each attached subscriber.