Skip to content

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

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.

./src/App.tsx
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

  1. The useSubscribeToCustomEvent automatically unsubscribes from the event on component unmount, so you do not need to worry about cleanups. However it does return a unsubscribe function back for cases where you want to take control of this. Once unsubscribe the event cannot be subscribed to again.

  2. 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

ParameterTypeDescriptionDefault
eventNamestringThe 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

ParameterTypeDescriptionDefault
unsubscribe()=>voidThe unsubscribe method for the event.N/A