mirror of
https://github.com/CompassConnections/Compass.git
synced 2026-03-26 02:21:06 -04:00
* Test * Add pretty formatting * Fix Tests * Fix Tests * Fix Tests * Fix * Add pretty formatting fix * Fix * Test * Fix tests * Clean typeckech * Add prettier check * Fix api tsconfig * Fix api tsconfig * Fix tsconfig * Fix * Fix * Prettier
19 lines
670 B
TypeScript
19 lines
670 B
TypeScript
// A hook soon to be added to the React core library:
|
|
// https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
|
|
// TODO: Once React adds this hook, use it instead.
|
|
|
|
import {useCallback, useRef} from 'react'
|
|
import {useSafeLayoutEffect} from './use-safe-layout-effect'
|
|
|
|
type AnyFunction = (...args: any[]) => any
|
|
|
|
export function useEvent<T extends AnyFunction>(callback?: T) {
|
|
const ref = useRef<AnyFunction | undefined>(() => {
|
|
throw new Error('Cannot call an event handler while rendering.')
|
|
})
|
|
useSafeLayoutEffect(() => {
|
|
ref.current = callback
|
|
})
|
|
return useCallback<AnyFunction>((...args) => ref.current?.apply(null, args), []) as T
|
|
}
|