Skip to content

Instantly share code, notes, and snippets.

@raibima
Created May 6, 2022 10:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raibima/b2b63b3fdc733faa694a90d351b5004f to your computer and use it in GitHub Desktop.
Save raibima/b2b63b3fdc733faa694a90d351b5004f to your computer and use it in GitHub Desktop.
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