useSubscribeToCustomEvent
Subscribe and manage lifecycle for a custom event.
The useSubscribeToCustomEvent hook is helpful when you want to subscribe and manage the lifecycle of your own custom events with payloads.
This is helpful in scenarios like flushing pending actions after auth is completed, clearing pending analytics queue based on user action or sucessful load of analytics scripts.
The hook can be used in conjunction with useDispatchCustomEvent.
For cases when you want to manage the entire lifecycle from one hook you can simply use useCustomEvent, with uses both useDispatchCustomEvent and useSubscribeToCustomEvent hooks internally.
useSubscribeToCustomEvent
window.state.value is :0
Usage
Import the hook from @abhushanaj/react-hooks and use in required component.
import React from 'react';import { useSubscribeToCustomEvent } from '@abhushanaj/react-hooks';
function App() { type Payload = { type: 'RESET'; newQueue: Array<unknown>; };
const unSubscribe = useSubscribeToCustomEvent<Payload>('queueChange', (e) => { console.log('Dispatched payload at', e.detail); });
return ( <div> <button onClick={unSubscribe}>Unsubscribe</button> </div> );}
export default App;Properties
-
The
useSubscribeToCustomEventautomatically unsubscribes from the event on component unmount, so you do not need to worry about cleanups. However it does return aunsubscribefunction back for cases where you want to take control of this. Once unsubscribe the event cannot be subscribed to again. -
You can use the generic
useSubscribeToCustomEvent<Payload>(eventName, callback)when you know the payload type. However, I recommend validating the payload first instead of relying on this approach.
API Reference
Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
| eventName | string | The name of the custom event name you want to dispatch. | N/A |
| eventCallback | (e: CustomEvent<T>=>void) | The callback which gets invoked when event is fired. | N/A |
Return Value
| Parameter | Type | Description | Default |
|---|---|---|---|
| unsubscribe | ()=>void | The unsubscribe method for the event. | N/A |