0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

負荷対策 ~ debounce ~

Posted at

経緯

とある案件で、位置情報を取得するケースがあり、位置情報が取得できた回数分React Hooksの副作用が動いてしまい、エラーが起きることがあった。そこで間引きを使って最後に取得した位置情報だけを利用したらうまく行ったので、同じようなことで困っている方の力になれたらと思いここに残そうと思いました。

もし、至らないところがあれば、ご指摘いただけたらと思います。

割と一般的な方法

const debounce = ((callback, interval) => {
  let timerId

  return (callback, interval) => {
    if (timerId) {
      clearTimeout(timerId)
    }

    timerId = setTimeout(() => {
      console.log('debounce:' + interval)
      callback()
    }, interval)
  }
})()

使い方

const CallBackGeo = () => {
  setGeoLocationState({
    latitude: latitude,
    longitude: longitude,
    accuracy: accuracy,
  })
}

debounce(CallBackGeo, 1000)

Custom Hooks

import { useState, useCallback, useRef } from 'react'

const useDebounceCallback = (callback, delay = 300) => {
  const [val, setVal] = useState()
  const decounceTimer = useRef(null)

  const dispatch = useCallback(
    (_val) => {
      clearTimeout(decounceTimer.current)

      decounceTimer.current = setTimeout(() => {
        setVal(callback(_val))
      }, delay)
    },
    [callback, delay, decounceTimer]
  )

  return [val, dispatch]
}

export default useDebounceCallback

使い方

  const double = useCallback((val) => {
    return val * 2
  }, [])

  const [DebounceDoubleValue, setDebounceDoubleValue] = useDebounceCallback(
    double,
    1000
  )

  const onStartGetPositionHandler = () => {
    setDebounceDoubleValue()
  }

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?