Skip to content

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.

./src/App.tsx
import React from 'react';
import { useCustomEvent } from '@abhushanaj/react-hooks';
function App() {
const [value, setValue] = React.useState(0);
const [dispatch, unSub] = useCustomEvent<{ newValue: number }>('valueChanged', (e) => {
setCount(e.detail.newValue);
});
return (
<div>
<p>Value is: {value}</p>
<button onClick={unSubscribe}>Unsubscribe</button>
<button
onClick={() => {
dispatch({ newValue: value++ });
}}
>
Unsubscribe
</button>
</div>
);
}
export default App;

Properties

  1. The useCustomEvent 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 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

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

The return value follows the [dispatch, unsubscribe] tuple.

ParameterTypeDescriptionDefault
dispatch(payload? T)=>voidThe dispatcher for the custom event which takes a payload as argument.N/A
unsubscribe()=>voidThe unsubscribe method for the event.N/A