This is my own hook which is used to realize debounce
in React Hooks
import { useMemo, useRef } from "react";
import { debounce } from "lodash";
export function useDebounceFn(fn, wait) {
const fnRef = useRef(fn)
fnRef.current = () => {
debugger
fn()
}
const debounceFn = useMemo(() => {
// can get the newest fn everytime
return debounce(() => {
fnRef.current()
});
// only can get the first fn
return debounce(fnRef.current);
}, []);
return {
run: debounceFn,
cancel: debounceFn.cancel,
}
}
I think debounce(fnRef.current)
is equal to debounce(() => { fnRef.current() }
,but the truth is that they are different and i wonder why. Is there any wrong with my code or just useMemo
do something different in these two cases.