-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added isDebouncing flag to useDebouncedValue
- Loading branch information
Showing
1 changed file
with
24 additions
and
5 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,44 @@ | ||
import { useEffect, useState } from 'react'; | ||
import { useEffect, useMemo, useState } from 'react'; | ||
|
||
/** | ||
* Debounces a value. | ||
* Returns the initial value immediately. | ||
* Returns the latest value after no changes have occurred for the debounce duration. | ||
* @param value Value to debounce | ||
* @param debounceMs Amount of time to debounce | ||
* @returns The debounced value | ||
* @returns The debounced value + whether the value is still debouncing | ||
*/ | ||
export function useDebouncedValue<T>(value: T, debounceMs: number): T { | ||
export function useDebouncedValue<T>( | ||
value: T, | ||
debounceMs: number | ||
): { isDebouncing: boolean; value: T } { | ||
const [isDebouncing, setIsDebouncing] = useState(true); | ||
const [debouncedValue, setDebouncedValue] = useState<T>(value); | ||
|
||
// Set isDebouncing to true immediately whenever the value changes. Using | ||
// `useMemo` instead of `useEffect` so that state is never out of sync whenever | ||
// value and / or debounceMs have changed. | ||
useMemo(() => { | ||
setIsDebouncing(true); | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [value, debounceMs]); | ||
|
||
useEffect(() => { | ||
let isCancelled = false; | ||
|
||
const timeoutId = setTimeout(() => { | ||
setDebouncedValue(value); | ||
if (!isCancelled) { | ||
setIsDebouncing(false); | ||
setDebouncedValue(value); | ||
} | ||
}, debounceMs); | ||
return () => { | ||
isCancelled = true; | ||
clearTimeout(timeoutId); | ||
}; | ||
}, [value, debounceMs]); | ||
|
||
return debouncedValue; | ||
return { isDebouncing, value: debouncedValue }; | ||
} | ||
|
||
export default useDebouncedValue; |