Remove TimeoutToggle callback's dependency on initial value

This commit is contained in:
Alejandro Celaya 2023-09-05 09:29:00 +02:00
parent 7a7884f38d
commit be1b474f41

View file

@ -15,16 +15,17 @@ export const useTimeoutToggle = (
clearTimeout = window.clearTimeout,
): [boolean, () => void] => {
const [flag, setFlag] = useState<boolean>(initialValue);
const initialValueRef = useRef(initialValue);
const timeout = useRef<number | undefined>(undefined);
const callback = useCallback(() => {
setFlag(!initialValue);
setFlag(!initialValueRef.current);
if (timeout.current) {
clearTimeout(timeout.current);
}
timeout.current = setTimeout(() => setFlag(initialValue), delay);
}, [clearTimeout, delay, initialValue, setTimeout]);
timeout.current = setTimeout(() => setFlag(initialValueRef.current), delay);
}, [clearTimeout, delay, setTimeout]);
return [flag, callback];
};