Skip to content

useDispatchCustomEvent

Dispatch a custom event with payload.

The useDispatchCustomEvent hook is helpful when you want to dispatch your own custom events with payloads that can be subscribed by any component in tree.

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

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.

useDispatchCustomEvent

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 { useDispatchCustomEvent } from '@abhushanaj/react-hooks';
function App() {
const dispatch = useDispatchCustomEvent('queueChange');
return (
<div>
<button
onClick={() => {
// dispatch a custom queueChange event with { type: 'RESET', newQueue: []} as payload.
dispatch({
type: 'RESET',
newQueue: []
});
}}
>
Reset Queue
</button>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
eventNamestringThe name of the custom event name you want to dispatch.N/A

Return Value

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