Skip to content

Instantly share code, notes, and snippets.

@chhornponleu
Created February 7, 2023 06:42
Show Gist options
  • Select an option

  • Save chhornponleu/6b43f4d90b24dc2e8067a17e4d0b86ac to your computer and use it in GitHub Desktop.

Select an option

Save chhornponleu/6b43f4d90b24dc2e8067a17e4d0b86ac to your computer and use it in GitHub Desktop.
useEffectEvent
/**
* original https://github.com/scottrippey/react-use-event-hook
*/
import { useLayoutEffect, useRef } from 'react';
type AnyFunction = (...args: any[]) => any;
function useEvent_shouldNotBeInvokedBeforeMount() {
console.warn(
'INVALID_USEEVENT_INVOCATION: the callback from useEvent cannot be invoked before the component has mounted.'
);
// throw new Error(
// 'INVALID_USEEVENT_INVOCATION: the callback from useEvent cannot be invoked before the component has mounted.'
// );
}
export function useEffectEvent<TCallback extends AnyFunction>(callback: TCallback): TCallback {
// Keep track of the latest callback:
const latestRef = useRef<TCallback>(useEvent_shouldNotBeInvokedBeforeMount as any);
useLayoutEffect(() => {
latestRef.current = callback;
}, [callback]);
const stableRef = useRef<TCallback>(null as any);
if (!stableRef.current) {
stableRef.current = function (...args) {
latestRef.current?.(...args);
} as TCallback;
}
return stableRef.current;
}
export default useEffectEvent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment