Skip to Content

useDebouncedCallback

Debounce a callback, such as an action call from a text input, with cancel and flush controls.

import { useDebouncedCallback } from "@osdk/react";

function useDebouncedCallback<TArgs extends readonly unknown[]>(
  callback: (...args: TArgs) => void | Promise<void>,
  delay: number,
): DebouncedCallback<TArgs>;

Returns a function that calls callback once delay milliseconds pass without another call. The latest callback is always used, and a pending call is cancelled when the component unmounts.

Parameters

ParameterTypeDescription
callback(...args: TArgs) => void | Promise<void>The function to debounce. A returned promise is not awaited, so handle its errors inside callback.
delaynumberMilliseconds to wait after the last call.

Returns

DebouncedCallback<TArgs>, a function with the same arguments as callback and two methods:

MemberTypeDescription
(...args)(...args: TArgs) => voidSchedules callback with these arguments and cancels any pending call.
cancel() => voidDrops the pending call.
flush() => voidRuns the pending call immediately.

Example

src/JobTitleInput.tsx
import { Employee, modifyEmployee } from "@my-app/sdk";
import { useDebouncedCallback, useOsdkAction } from "@osdk/react";

export function JobTitleInput({ employee }: { employee: Employee.OsdkInstance }) {
  const { applyAction, error } = useOsdkAction(modifyEmployee);

  const save = useDebouncedCallback(async (jobTitle: string) => {
    try {
      await applyAction({ employee, jobTitle });
    } catch {
      // The hook result exposes the failure as error.
    }
  }, 500);

  return (
    <>
      <input
        defaultValue={employee.jobTitle}
        onChange={(e) => save(e.target.value)}
      />
      {error && <p role="alert">Could not save.</p>}
    </>
  );
}

See also

On this page