Created
August 10, 2021 20:05
-
-
Save itsMapleLeaf/8451314160f5b3e8e10fedd0fe151765 to your computer and use it in GitHub Desktop.
react debounce and throttle hooks
This file contains hidden or 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 { useEffect, useRef, useState } from "react" | |
export function useDebouncedValue<T>( | |
sourceValue: T, | |
ms: number | undefined | |
): T { | |
const [value, setValue] = useState(sourceValue) | |
useEffect(() => { | |
if (ms == null) return | |
const timeout = setTimeout(() => { | |
setValue(sourceValue) | |
}, ms) | |
return () => clearTimeout(timeout) | |
}, [sourceValue, ms]) | |
return value | |
} | |
export function useThrottledValue<T>( | |
sourceValue: T, | |
ms: number | undefined | |
): T { | |
const sourceValueRef = useRef(sourceValue) | |
useEffect(() => { | |
sourceValueRef.current = sourceValue | |
}) | |
const [value, setValue] = useState(sourceValue) | |
useEffect(() => { | |
if (ms == null) return | |
const interval = setInterval(() => { | |
setValue(sourceValueRef.current) | |
}, ms) | |
return () => clearInterval(interval) | |
}, [ms]) | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment