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.
Properties
-
The
useSubscribeToCustomEvent
automatically unsubscribes from the event on component unmount, so you do not need to worry about cleanups. However it does return aunsubscribe
function 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 |