Handle scroll event will fire to often. What is the way to slowdown/debounce it?
And if it's possible, i want last event always be fired and not skipped.
const handleScroll = event => {
//how to debounse scroll change?
//if you will just setValue here, it's will lag as hell on scroll
}
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => {
window.removeEventListener('scroll', handleScroll)
}
}, [])
Here is the useDebounce hook example from xnimorz
import { useState, useEffect } from 'react'
export const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(
() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
},
[value, delay]
)
return debouncedValue
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…