9

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
}
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105

2 Answers2

12

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 1
    So i need Lodash library for this _.debounce to work? Is there a way without external library? – ZiiMakc Jan 06 '19 at 13:44
  • 6
    You will need to write this functionality yourself. At this point this isn't specific to React or hooks. See https://stackoverflow.com/questions/20695334/is-this-a-simple-debounce-function-in-javascript . This is not a productive way to do things because this is what libraries exist for. FWIW, Lodash implementation offers much better performance than naive setTimeout implementation. – Estus Flask Jan 06 '19 at 13:52
  • 1
    if you don't want to import lodash entirely you can just use this : https://www.npmjs.com/package/lodash.debounce – Rose Dec 01 '21 at 18:16
  • why do you use 100? can you explain? – Flezcano Nov 08 '22 at 04:44
  • 1
    @Flezcano It's random number, just enough to prevent it from being triggered 10s times per second but small enough to be nearly instant – Estus Flask Nov 08 '22 at 07:30
0
const debounceLoadData = useCallback(debounce((debounceValue)=>{  
    props.setSenderAddress(debounceValue)
}, 300), []);
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Antier Solutions
  • 1,326
  • 7
  • 10