Created
May 6, 2022 10:22
-
-
Save raibima/b2b63b3fdc733faa694a90d351b5004f 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