UNPKG

use-state-debounced

Version:

useStateDebounced - React debounced state hook

1 lines 1.51 kB
{"version":3,"sources":["../src/useStateDebounced.ts"],"sourcesContent":["import {\n Dispatch, SetStateAction, useEffect, useState,\n} from 'react';\n\ntype ReturnType<S> = [S, S, Dispatch<SetStateAction<S>>];\n\n// Typescript function overloading with and without 'initialState'\nexport function useStateDebounced<S>(delay: number, initialState: S | (() => S)): ReturnType<S>;\nexport function useStateDebounced<S = undefined>(delay: number): ReturnType<S | undefined>;\n\n// Like useState but debounced. This hook allows you to debounce any fast changing value. The debounced\n// value will only reflect the latest value when the setValue has not been called for the specified time period.\nexport function useStateDebounced<S>(delay: number, initialState?: S | (() => S)): ReturnType<S | undefined> {\n const [value, setValue] = useState(initialState);\n const [debouncedValue, setDebouncedValue] = useState(value);\n\n useEffect(() => {\n const timer = setTimeout(() => setDebouncedValue(value), delay);\n\n return () => {\n clearTimeout(timer);\n };\n }, [value, delay]);\n\n return [value, debouncedValue, setValue];\n}\n"],"mappings":";AAAA;AAAA,EAC4B;AAAA,EAAW;AAAA,OAChC;AAUA,SAAS,kBAAqB,OAAe,cAAyD;AAC3G,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,YAAY;AAC/C,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,SAAS,KAAK;AAE1D,YAAU,MAAM;AACd,UAAM,QAAQ,WAAW,MAAM,kBAAkB,KAAK,GAAG,KAAK;AAE9D,WAAO,MAAM;AACX,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,OAAO,KAAK,CAAC;AAEjB,SAAO,CAAC,OAAO,gBAAgB,QAAQ;AACzC;","names":[]}