Files
siftlode/frontend/src/lib/useDebounced.ts
T
peter 2d5bd275fa fix(diagnostics): a pivot or Back applies the search text at once
The query read the typing-debounced search, so for 300 ms after a jump it mixed the new view's
filters with the old view's text and fetched rows neither view shows. useDebounced takes a settle key
whose change applies the value immediately.
2026-09-19 05:47:16 +02:00

24 lines
1021 B
TypeScript

import { useEffect, useState } from "react";
// Returns `value` after it has stopped changing for `delay` ms. Lets a text input stay
// responsive (it owns the immediate value) while the query it drives only re-runs once the
// user pauses — so we don't refetch the feed on every keystroke.
//
// `settle`: a change of it takes `value` at once. A value that did not come from typing (Back
// restoring a search, a pivot clearing one) has no keystrokes to wait out, and the lag only ran a
// query mixing the new filters with the old text (deep-review 2026-09-19).
export function useDebounced<T>(value: T, delay = 300, settle?: unknown): T {
const [debounced, setDebounced] = useState(value);
const [settled, setSettled] = useState(settle);
useEffect(() => {
const id = window.setTimeout(() => setDebounced(value), delay);
return () => window.clearTimeout(id);
}, [value, delay]);
if (settle !== settled) {
setSettled(settle);
setDebounced(value);
return value;
}
return debounced;
}