Debounces another state values changes by the given delay.
This can be used to debounce the execution of another effect tied to search inputs
or other fast changing values
.
import { useState, useEffect } from "react"export default function useDebouncedValue(value, delay) {const [debouncedValue, setDebouncedValue] = useState(value)useEffect(() => {const timeout = setTimeout(() => {setDebouncedValue(value)}, delay)return () => {clearTimeout(timeout)}}, [value])return debouncedValue}
Pass another state value and a delay to useDebouncedValue
.
function MyComponent() {// Controls an input for exampleconst [searchText, setSearchText] = useState("")// Only changes if 500ms passed after the last change of searchTextconst debouncedSearchText = useDebouncedValue(searchText, 500)useEffect(() => {// Do some api calls}, [debouncedSearchText])// ...}