mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
at verify-code 23 lines 881 B view raw
1import {useCallback, useInsertionEffect, useRef} from 'react' 2 3// This should be used sparingly. It erases reactivity, i.e. when the inputs 4// change, the function itself will remain the same. This means that if you 5// use this at a higher level of your tree, and then some state you read in it 6// changes, there is no mechanism for anything below in the tree to "react" 7// to this change (e.g. by knowing to call your function again). 8// 9// Also, you should avoid calling the returned function during rendering 10// since the values captured by it are going to lag behind. 11export function useNonReactiveCallback<T extends Function>(fn: T): T { 12 const ref = useRef(fn) 13 useInsertionEffect(() => { 14 ref.current = fn 15 }, [fn]) 16 return useCallback( 17 (...args: any) => { 18 const latestFn = ref.current 19 return latestFn(...args) 20 }, 21 [ref], 22 ) as unknown as T 23}