All files / src/hooks useEventHandler.ts

83.33% Statements 5/6
100% Branches 0/0
66.66% Functions 2/3
83.33% Lines 5/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 191x                 36x 36x 36x     36x        
import React from 'react';
 
/*
 * TODO: move to @gravity-ui/uikit
 * The hook returns a stable function (an empty list of dependencies),
 * but this function always calls the actual function associated with the last render.
 * The returned function should be used as an event handler or inside a useEffect.
 */
export function useEventHandler<T extends Function>(handler?: T) {
    const ref = React.useRef<T | undefined>(handler);
    React.useLayoutEffect(() => {
        ref.current = handler;
    }, [handler]);
    // @ts-expect-error
    return React.useCallback<T>((...args) => {
        return ref.current?.(...args);
    }, []);
}