📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

React hook useDebounce

The debounce hook is a great way to improve the performance of your React applications. It allows you to throttle the execution of a function so that it only runs after a certain amount of time has passed. This is especially useful for expensive operations like fetching data from an API.

import { useEffect } from 'react';
import useTimeoutFn from './useTimeoutFn';

export default function useDebounce(fn, ms = 0, deps = []){
  const [isReady, cancel, reset] = useTimeoutFn(fn, ms);

  useEffect(reset, deps);

  return [isReady, cancel];
}

useTimeoutFn.js

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

export default function useTimeoutFn(fn, ms = 0) {
  const ready = useRef(false);
  const timeout = useRef();
  const callback = useRef(fn);
  const isReady = useCallback(() => ready.current, []);

const set = useCallback(() => {
    ready.current = false;
    timeout.current && clearTimeout(timeout.current);
    timeout.current = setTimeout(() => {
      ready.current = true;
      callback.current();
    }, ms);
  }, [ms]);

  const clear = useCallback(() => {
    ready.current = null;
    timeout.current && clearTimeout(timeout.current);
  }, []);

  useEffect(() => {
    callback.current = fn;
  }, [fn]);

  useEffect(() => {
    set();
    return clear;
  }, [ms]);

  return [isReady, clear, set];
}