import { useRef, useEffect, useCallback } from 'react';

/**
 * Calls the function `debounce` milliseconds after the last time the function
 * is called (trailing debounce). Any change to deps will reset the timer, not
 * calling the function.
 *
 * @param {function} callback
 * @param {integer} debounce
 * @param {array} deps
 */

var useDebounce = function useDebounce(callback, debounce) {
  var timeout = useRef();
  var cb = useRef();
  useEffect(function () {
    cb.current = callback;
  }, [callback]);
  var cancel = useCallback(function () {
    clearTimeout(timeout.current);
  }, [timeout.current]);
  useEffect(function () {
    cancel();
  }, [debounce]);
  var debounced = useCallback(function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    cancel();
    timeout.current = setTimeout(function () {
      cb.current.apply(cb, args);
    }, debounce);
  }, [debounce]);
  return [debounced, cancel];
};

export { useDebounce as default };
