Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
11 views
in Technique[技术] by (71.8m points)

reactjs - How to slowdown/debounce events handling with react hooks?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Event handler that uses hooks can be debounced done the same way as any other function with any debounce implementation, e.g. Lodash:

  const updateValue = _.debounce(val => {
    setState(val);
  }, 100);

  const handleScroll = event => {
    // process event object if needed
    updateValue(...);
  }

Notice that due to how React synthetic events work, event object needs to be processed synchronously if it's used in event handler.

last event always be fired and not skipped

It's expected that only the last call is taken into account with debounced function, unless the implementation allows to change this, e.g. leading and trailing options in Lodash debounce.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...