Last active
November 17, 2023 09:12
-
-
Save csandman/cb1b9cae2334415b0b20e04b228c1016 to your computer and use it in GitHub Desktop.
Debounce useSwr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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