(fn: T)
| 10 | ) => ReturnType<T>; |
| 11 | |
| 12 | export function useEvent<T extends Noop>(fn: T) { |
| 13 | if (process.env.NODE_ENV === 'development') { |
| 14 | if (typeof fn !== 'function') { |
| 15 | console.error( |
| 16 | `useMemoizedFn expected parameter is a function, got ${typeof fn}` |
| 17 | ); |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | const fnRef = useRef<T>(fn); |
| 22 | |
| 23 | // why not write `fnRef.current = fn`? |
| 24 | // https://github.com/alibaba/hooks/issues/728 |
| 25 | fnRef.current = useMemo(() => fn, [fn]); |
| 26 | |
| 27 | const memoizedFn = useRef<PickFunction<T>>(); |
| 28 | if (!memoizedFn.current) { |
| 29 | memoizedFn.current = function (this, ...args) { |
| 30 | return fnRef.current.apply(this, args); |
| 31 | }; |
| 32 | } |
| 33 | |
| 34 | return memoizedFn.current as T; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Same with useEvent but return loading state |
no test coverage detected