Skip to content

fix(site): speed up state syncs and validate input for debounce hook logic #18877

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

Merged
merged 10 commits into from
Jul 17, 2025
Next Next commit
fix(site): speed up state syncs and add input validation for debounce…
… hook logic
  • Loading branch information
Parkreiner committed Jul 15, 2025
commit 9f35d9ba38b4e139a001d3d01559133de9c27690
62 changes: 39 additions & 23 deletions site/src/hooks/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,15 @@
* @file Defines hooks for created debounced versions of functions and arbitrary
* values.
*
* It is not safe to call a general-purpose debounce utility inside a React
* render. It will work on the initial render, but the memory reference for the
* value will change on re-renders. Most debounce functions create a "stateful"
* version of a function by leveraging closure; but by calling it repeatedly,
* you create multiple "pockets" of state, rather than a centralized one.
*
* Debounce utilities can make sense if they can be called directly outside the
* component or in a useEffect call, though.
* It is not safe to call most general-purpose debounce utility functions inside
* a React render. This is because the state for handling the debounce logic
* lives in the utility instead of React. If you call a general-purpose debounce
* function inline, that will create a new stateful function on every render,
* which has a lot of risks around conflicting/contradictory state.
*/
import { useCallback, useEffect, useRef, useState } from "react";

type useDebouncedFunctionReturn<Args extends unknown[]> = Readonly<{
type UseDebouncedFunctionReturn<Args extends unknown[]> = Readonly<{
debounced: (...args: Args) => void;

// Mainly here to make interfacing with useEffect cleanup functions easier
Expand All @@ -34,12 +31,18 @@ type useDebouncedFunctionReturn<Args extends unknown[]> = Readonly<{
*/
export function useDebouncedFunction<
// Parameterizing on the args instead of the whole callback function type to
// avoid type contra-variance issues
// avoid type contravariance issues
Args extends unknown[] = unknown[],
>(
callback: (...args: Args) => void | Promise<void>,
debounceTimeMs: number,
): useDebouncedFunctionReturn<Args> {
): UseDebouncedFunctionReturn<Args> {
if (!Number.isInteger(debounceTimeMs) || debounceTimeMs < 0) {
throw new Error(
`Provided debounce value ${debounceTimeMs} is not a non-negative integer`,
);
}

const timeoutIdRef = useRef<number | null>(null);
const cancelDebounce = useCallback(() => {
if (timeoutIdRef.current !== null) {
Expand Down Expand Up @@ -81,19 +84,32 @@ export function useDebouncedFunction<
/**
* Takes any value, and returns out a debounced version of it.
*/
export function useDebouncedValue<T = unknown>(
value: T,
debounceTimeMs: number,
): T {
const [debouncedValue, setDebouncedValue] = useState(value);
export function useDebouncedValue<T>(value: T, debounceTimeoutMs: number): T {
Copy link
Member Author

@Parkreiner Parkreiner Jul 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the default parameter here because if you, the user of the hook, don't know the type of a value you're trying to debounce, you're probably doing something really wrong

if (!Number.isInteger(debounceTimeoutMs) || debounceTimeoutMs < 0) {
throw new Error(
`Provided debounce value ${debounceTimeoutMs} is not a non-negative integer`,
);
}

useEffect(() => {
const timeoutId = window.setTimeout(() => {
setDebouncedValue(value);
}, debounceTimeMs);
const [debounced, setDebounced] = useState(value);

// If the debounce timeout is ever zero, synchronously flush any state syncs.
// Doing this mid-render instead of in useEffect means that we drastically cut
// down on needless re-renders, and we also avoid going through the event loop
// to do a state sync that is *intended* to happen immediately
if (value !== debounced && debounceTimeoutMs === 0) {
setDebounced(value);
}
useEffect(() => {
if (debounceTimeoutMs === 0) {
return;
}

return () => window.clearTimeout(timeoutId);
}, [value, debounceTimeMs]);
const timeoutId = window.setTimeout(() => {
setDebounced(value);
}, debounceTimeoutMs);
return () => window.clearTimeout(timeoutId);
}, [value, debounceTimeoutMs]);

return debouncedValue;
return debounced;
}