Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: DH-16336: usePickerWithSelectedValues - boolean flags should be calculated based on trimmed search text #1750

Merged
merged 4 commits into from
Jan 31, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions packages/react-hooks/src/useDebouncedValue.ts
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);
bmingles marked this conversation as resolved.
Show resolved Hide resolved
// 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;
Loading