Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created August 10, 2021 20:05
Show Gist options
  • Save itsMapleLeaf/8451314160f5b3e8e10fedd0fe151765 to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/8451314160f5b3e8e10fedd0fe151765 to your computer and use it in GitHub Desktop.
react debounce and throttle hooks
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