Skip to content

Instantly share code, notes, and snippets.

@csandman
Last active November 17, 2023 09:12
Show Gist options
  • Save csandman/cb1b9cae2334415b0b20e04b228c1016 to your computer and use it in GitHub Desktop.
Save csandman/cb1b9cae2334415b0b20e04b228c1016 to your computer and use it in GitHub Desktop.
Debounce useSwr
// originally from: https://github.com/vercel/swr/issues/110#issuecomment-552637429
import useSWR from 'swr';
import useDebounce from 'hooks/use-debounce';
const App = () => {
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 1000);
const { data: res, isValidating } = useSWR(
() => debouncedSearch ? `/api/suggestion?value=${debouncedSearch}` : null,
Api.fetcher,
);
return null;
}
export default App;
import { useState, useEffect } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment