{"version":3,"file":"use-debounced-state.cjs","names":[],"sources":["../../src/use-debounced-state/use-debounced-state.ts"],"sourcesContent":["import { SetStateAction, useCallback, useEffect, useRef, useState } from 'react';\n\nexport interface UseDebouncedStateOptions {\n  leading?: boolean;\n}\n\nexport type UseDebouncedStateReturnValue<T> = [T, (newValue: SetStateAction<T>) => void];\n\nexport function useDebouncedState<T = any>(\n  defaultValue: T,\n  wait: number,\n  options: UseDebouncedStateOptions = { leading: false }\n): UseDebouncedStateReturnValue<T> {\n  const [value, setValue] = useState(defaultValue);\n  const timeoutRef = useRef<number | null>(null);\n  const leadingRef = useRef(true);\n\n  const clearTimeout = () => window.clearTimeout(timeoutRef.current!);\n  useEffect(() => clearTimeout, []);\n\n  const debouncedSetValue = useCallback(\n    (newValue: SetStateAction<T>) => {\n      clearTimeout();\n      if (leadingRef.current && options.leading) {\n        setValue(newValue);\n      } else {\n        timeoutRef.current = window.setTimeout(() => {\n          leadingRef.current = true;\n          setValue(newValue);\n        }, wait);\n      }\n      leadingRef.current = false;\n    },\n    [options.leading, wait]\n  );\n\n  return [value, debouncedSetValue] as const;\n}\n\nexport namespace useDebouncedState {\n  export type Options = UseDebouncedStateOptions;\n  export type ReturnValue<T> = UseDebouncedStateReturnValue<T>;\n}\n"],"mappings":";;;AAQA,SAAgB,kBACd,cACA,MACA,UAAoC,EAAE,SAAS,MAAM,GACpB;CACjC,MAAM,CAAC,OAAO,aAAA,GAAA,MAAA,UAAqB,YAAY;CAC/C,MAAM,cAAA,GAAA,MAAA,QAAmC,IAAI;CAC7C,MAAM,cAAA,GAAA,MAAA,QAAoB,IAAI;CAE9B,MAAM,qBAAqB,OAAO,aAAa,WAAW,OAAQ;CAClE,CAAA,GAAA,MAAA,iBAAgB,cAAc,CAAC,CAAC;CAkBhC,OAAO,CAAC,QAAA,GAAA,MAAA,cAfL,aAAgC;EAC/B,aAAa;EACb,IAAI,WAAW,WAAW,QAAQ,SAChC,SAAS,QAAQ;OAEjB,WAAW,UAAU,OAAO,iBAAiB;GAC3C,WAAW,UAAU;GACrB,SAAS,QAAQ;EACnB,GAAG,IAAI;EAET,WAAW,UAAU;CACvB,GACA,CAAC,QAAQ,SAAS,IAAI,CAGO,CAAC;AAClC"}