UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

1 lines 1.95 kB
{"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]\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,OAAO,EACrB;CACjC,MAAM,CAAC,OAAO,aAAA,GAAA,MAAA,UAAqB,aAAa;CAChD,MAAM,cAAA,GAAA,MAAA,QAAmC,KAAK;CAC9C,MAAM,cAAA,GAAA,MAAA,QAAoB,KAAK;CAE/B,MAAM,qBAAqB,OAAO,aAAa,WAAW,QAAS;AACnE,EAAA,GAAA,MAAA,iBAAgB,cAAc,EAAE,CAAC;AAkBjC,QAAO,CAAC,QAAA,GAAA,MAAA,cAfL,aAAgC;AAC/B,gBAAc;AACd,MAAI,WAAW,WAAW,QAAQ,QAChC,UAAS,SAAS;MAElB,YAAW,UAAU,OAAO,iBAAiB;AAC3C,cAAW,UAAU;AACrB,YAAS,SAAS;KACjB,KAAK;AAEV,aAAW,UAAU;IAEvB,CAAC,QAAQ,QAAQ,CAClB,CAEgC"}