I'm trying to write custom hooks but I'm facing an issue whenever I want function as arguments.
I want to write a useDebouce hook; From example around the web I ended up with this:
import { useCallback, useEffect } from 'react';
import debounce from 'lodash/debounce';
const useDebounce = (fn, time, options) => {
useEffect(() => console.log('reset'), [fn, time, options]);
return useCallback(debounce(fn, time, options), [fn, time, options]);
};
I want to reset whenever an argument change.
However if I use it like this:
const randomComponent = () => {
const doSomething = useDebounce(() => console.log('test'), 500, {maxWait: 1000});
// ...
};
Every time my component renders the function and object reference change (1st and 3rd arguments), which means I end up creating a new debounced function everytime. So the debounce behavior doesn't work.
What is the best way to deal with callback references changing at every render ?