useCustomEvent
Manage the entire lifecycle for a custom event.
The useCustomEvent
hook is helpful when you want manage the entire lifecycle for a custom event. From dispatch, to subscribing and cleanup, it’s a one off solution.
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 is composed using the useDispatchCustomEvent and useSubscribeToCustomEvent hooks.
useCustomEvent
window.state.value is :0
Update the window.state.value from console and see it reflect above.The example above is simply creating a proxy over window.state and for every set action performed on it, dispatching action which the component is subscribing to.Usage
Import the hook from @abhushanaj/react-hooks
and use in required component.
Properties
-
The
useCustomEvent
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
useCustomEvent<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
The return value follows the [dispatch, unsubscribe]
tuple.
Parameter | Type | Description | Default |
---|---|---|---|
dispatch | (payload? T)=>void | The dispatcher for the custom event which takes a payload as argument. | N/A |
unsubscribe | ()=>void | The unsubscribe method for the event. | N/A |