@zohodesk/hooks
Version:
Unified Component Library - Hooks
19 lines (17 loc) • 585 B
JavaScript
import { useRef, useCallback, useLayoutEffect } from 'react';
/**
* refer: https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
* @param {*} handler
* @returns
*/
export default function useEvent(handler) {
const handlerRef = useRef(null); // In a real implementation, this would run before layout effects
useLayoutEffect(() => {
handlerRef.current = handler;
});
return useCallback(function () {
// In a real implementation, this would throw if called during render
const fn = handlerRef.current;
return fn && fn(...arguments);
}, []);
}