Created
March 23, 2023 15:35
-
-
Save AndrewIngram/2e5d530eb91b96c6a1b009b21c59db52 to your computer and use it in GitHub Desktop.
useEffectEventShim.ts
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 { 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