Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useDebounce types improvement #94

Closed
soywod opened this issue Feb 1, 2019 · 1 comment
Closed

useDebounce types improvement #94

soywod opened this issue Feb 1, 2019 · 1 comment

Comments

@soywod
Copy link

soywod commented Feb 1, 2019

I would like to propose a better typed version of your useDebounce, here my actual step:

import { useEffect, useRef } from 'react';
import cloneDeep from 'lodash/fp/cloneDeep';
import noop from 'lodash/fp/noop';

// ------------------------------------------------------------ # Type aliases #

type AnyCallback = (...args: any[]) => any;
type Debounce<Callback extends AnyCallback> = (...params: Parameters<Callback>) => void;

// -------------------------------------------------------------------- # Hook #

export default function useDebounce() {
  return <Callback extends AnyCallback>(callback: Callback, delay = 250) => {
    const timer = useRef<NodeJS.Timeout>(null);
    const debounce = useRef<Debounce<Callback>>(noop);

    useEffect(() => {
      debounce.current = (...params: Parameters<Callback>) => {
        const paramsCopy = cloneDeep(params);

        if (timer.current) {
          clearTimeout(timer.current);
        }

        // @ts-ignore
        // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065
        timer.current = setTimeout(() => callback(...paramsCopy), delay);
      };
    }, []);

    return debounce.current;
  };
}

Usage:

import useDebounce from './path/to/useDebounce'

function Component() {
  const debounce = useDebounce()

  function handleClick(event: React.ChangeEvent<HTMLInputElement>) {
    console.log('Clicked with debounce')
  }

  return <input type="text" onChange={debounce(handleClick)} />
}

Any remark will be highly appreciated!

@benneq
Copy link
Contributor

benneq commented Feb 2, 2019

I think you shouldn't break the existing API without backwards compatibility

@soywod soywod closed this as completed Mar 1, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants