Skip to content

Instantly share code, notes, and snippets.

@mcousillas6
Created June 2, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcousillas6/1c69a5d67e1fa9367b6d88ce6a478d92 to your computer and use it in GitHub Desktop.
Save mcousillas6/1c69a5d67e1fa9367b6d88ce6a478d92 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
export const useDebouncedState = <T>(initialValue: T, delay: number) => {
const [value, setValue] = useState(initialValue);
const [debouncedValue, setDebouncedValue] = useState(initialValue);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return [value, debouncedValue, setValue] as const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment