-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
23 lines (21 loc) · 853 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useCallback, useRef } from 'react';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useRecapture<P extends any[] = any[], R = void>(
initialValue?: (...args: P) => R,
): [(...args: P) => R, (callback?: ((...args: P) => R) | null) => void] {
const ref = useRef<(...args: P) => R>(initialValue);
const stableRef = useCallback((...args: P) => ref.current?.(...args), [ref]);
const recapture = useCallback(
(callback?: ((...args: P) => R) | null) => (ref.current = callback),
[ref],
);
return [stableRef, recapture];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useEventEffect<P extends any[] = any[]>(
eventEffect: (...args: P) => void,
) {
const [callback, recapture] = useRecapture<P, void>(eventEffect);
recapture(eventEffect);
return callback;
}