-
-
Save Bigismall/91d9f418765e0df21640dd718058e252 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
import { useRef, useCallback, useInsertionEffect } from "react"; | |
let _dispatcher = null; | |
function getCurrentDispatcher() { | |
return React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED | |
.ReactCurrentDispatcher.current; | |
} | |
function useRenderTracker() { | |
if (_dispatcher === null) { | |
_dispatcher = getCurrentDispatcher(); | |
} | |
} | |
function isInRender() { | |
return _dispatcher !== null && _dispatcher === getCurrentDispatcher(); | |
} | |
export function useEvent(handler) { | |
useRenderTracker(); | |
const ref = useRef(null); | |
useInsertionEffect(() => { | |
ref.current = handler; | |
}); | |
return useCallback((...args) => { | |
if (isInRender()) { | |
throw new Error("Cannot call event in Render!"); | |
} | |
const fn = ref.current; | |
fn(...args); | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment