How to slowdown/debounce events handling with react hooks?

ZiiMakc picture ZiiMakc · Jan 6, 2019 · Viewed 7.4k times · Source

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
}

Answer

Estus Flask picture Estus Flask · Jan 6, 2019

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.