Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewIngram/2e5d530eb91b96c6a1b009b21c59db52 to your computer and use it in GitHub Desktop.
Save AndrewIngram/2e5d530eb91b96c6a1b009b21c59db52 to your computer and use it in GitHub Desktop.
useEffectEventShim.ts
import { useRef, useCallback, useInsertionEffect } from "react";
// Approximation of React's upcoming useEffectEvent hook
// This gives us a non-reactive effect event callback, it will always use the latest version of
// the callback, rather than the one that was closed over.
export default function useEffectEventShim<T extends (...args: any[]) => any>(
fn: T
): (...funcArgs: Parameters<T>) => ReturnType<T> {
const ref = useRef(fn);
useInsertionEffect(() => {
ref.current = fn;
}, [fn]);
return useCallback((...args: Parameters<T>): ReturnType<T> => {
const f = ref.current;
return f(...args);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment