2022-03-31 07:22:36 -04:00
|
|
|
import { useCallback, useRef } from 'react'
|
2021-11-15 11:33:57 -05:00
|
|
|
|
|
|
|
export default function useCallbackHandlers() {
|
2023-01-09 09:33:43 -05:00
|
|
|
const handlersRef = useRef(new Set<(...arg: unknown[]) => void>())
|
2021-11-15 11:33:57 -05:00
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
const addHandler = useCallback((handler: (...args: unknown[]) => void) => {
|
2022-03-31 07:22:36 -04:00
|
|
|
handlersRef.current.add(handler)
|
|
|
|
}, [])
|
2021-11-15 11:33:57 -05:00
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
const deleteHandler = useCallback((handler: (...args: unknown[]) => void) => {
|
2022-03-31 07:22:36 -04:00
|
|
|
handlersRef.current.delete(handler)
|
|
|
|
}, [])
|
2021-11-15 11:33:57 -05:00
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
const callHandlers = useCallback((...args: unknown[]) => {
|
2022-03-31 07:22:36 -04:00
|
|
|
for (const handler of handlersRef.current) {
|
|
|
|
handler(...args)
|
|
|
|
}
|
|
|
|
}, [])
|
2021-11-15 11:33:57 -05:00
|
|
|
|
|
|
|
return { addHandler, deleteHandler, callHandlers }
|
|
|
|
}
|