Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 247
ZiiMakc Avatar asked Jan 06 '19 12:01

ZiiMakc


1 Answers

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.

like image 103
Estus Flask Avatar answered Nov 05 '22 16:11

Estus Flask