@lucas-barake/effect-form-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Internal debounce hook for form validation.
3
+ *
4
+ * @internal
5
+ */
6
+ import * as React from "react"
7
+
8
+ /**
9
+ * Hook that debounces a callback function.
10
+ *
11
+ * @internal
12
+ */
13
+ export const useDebounced = <T extends (...args: ReadonlyArray<any>) => void>(
14
+ fn: T,
15
+ delayMs: number | null,
16
+ ): T => {
17
+ const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)
18
+ const fnRef = React.useRef(fn)
19
+
20
+ React.useEffect(() => {
21
+ fnRef.current = fn
22
+ })
23
+
24
+ React.useEffect(() => {
25
+ return () => {
26
+ if (timeoutRef.current !== null) {
27
+ clearTimeout(timeoutRef.current)
28
+ }
29
+ }
30
+ }, [])
31
+
32
+ return React.useMemo(
33
+ () =>
34
+ ((...args: Parameters<T>) => {
35
+ if (delayMs === null || delayMs === 0) {
36
+ fnRef.current(...args)
37
+ return
38
+ }
39
+ if (timeoutRef.current !== null) {
40
+ clearTimeout(timeoutRef.current)
41
+ }
42
+ timeoutRef.current = setTimeout(() => {
43
+ fnRef.current(...args)
44
+ timeoutRef.current = null
45
+ }, delayMs)
46
+ }) as T,
47
+ [delayMs],
48
+ )
49
+ }