Skip to content

useListener

Category
Export Size
186 B
Last Changed
5 days ago

Bind a callback to a listener registration function returned by a reause hook, with automatic cleanup on unmount.

Demo

Usage

tsx
import { 
createEventHook
,
useListener
} from '@reause/shared'
const
resultEvent
=
createEventHook
<Response>()
useListener
(
resultEvent
, (
response
) => {
console
.
log
(
response
)
}) // elsewhere — deliver an event:
resultEvent
.
trigger
(response)

The registration returns the off function itself, so when the component unmounts the listener is automatically unregistered — listeners never leak and callbacks never fire after the component is gone. (An on that returns nothing provides no cleanup, so that guarantee cannot be made.)

useListener accepts either form of the subscription source:

tsx
// the registration function itself
useListener
(resultEvent.on, callback)
// or any object exposing it as `on` — e.g. a `createEventHook()` result
useListener
(resultEvent, callback)

The callback is kept in a ref: changing cb across renders does not re-register the listener — the latest callback is used by the already-registered listener. Only when the source itself changes (a new hook instance, or a new event hook object) does the effect re-run, unregistering the old listener and registering the new one.

Type Declarations

ts
export type ListenerOn<T extends (...args: any[]) => void> = (fn: T) => (() => void) | void

export function useListener<T extends (...args: any[]) => void>(on: ListenerOn<T> | {
    on: ListenerOn<T>;
}, cb: T): void

Source

Source · Demo

Contributors

hairyf

Changelog

v0.1.7 on
534c2 - refactor(shared)!: return the off function from listener registrars
v0.1.0 on
0ec95 - fix(shared): resolve useListener audit findings (#741)

Released under the MIT License. v0.1.8