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

add useDebouncedValue hook #1948

Open
ianstormtaylor opened this issue Apr 15, 2021 · 2 comments
Open

add useDebouncedValue hook #1948

ianstormtaylor opened this issue Apr 15, 2021 · 2 comments

Comments

@ianstormtaylor
Copy link

Is your feature request related to a problem? Please describe.
The issue is when using hooks like useMeasure where a value might change many times per second as someone is resizing.

One solution could be changing useMeasure, but then every hook that needs to be debounced has to take options. Instead, it would be nice to have a useDebouncedValue that can take a quickly-changing value but only reflect the changes after a time. It would be just like useDebounce but a value instead of a function.

const debouncedValue = useDebouncedValue(someRapidlyChangingValue, 200)
@MiroslavPetrik
Copy link

import { useMemo, useState } from "react";
import { useDeepCompareEffect } from "react-use";
import { debounce } from "lodash";

export const useDebouncedValue = <T>(value: T, timeout = 1000) => {
  const [debounced, setDebounced] = useState(value);

  const debounceValue = useMemo(
    () => debounce((value) => setDebounced(value), timeout),
    [setDebounced, timeout]
  );

  useDeepCompareEffect(() => {
    debounceValue(value);
  }, [value]);

  return debounced;
};

Demo

@vincerubinetti
Copy link

@MiroslavPetrik Nice, pretty clean. Btw you don't need setDebounced in the dep array.

Wish this was built in.

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

4 participants
@ianstormtaylor @vincerubinetti @MiroslavPetrik and others