Skip to content

Commit b28088f

Browse files
committed
Add use-debounced-state
1 parent cb7e4cf commit b28088f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

hooks/use-debounced-state.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { useEffect, useState } from 'react'
2+
3+
const DEFAULT_TIMEOUT_MS = 1000
4+
5+
/**
6+
* Debounced setState
7+
* @param initial The initial state value
8+
* @param timeoutMs The debounce interval
9+
* @returns [state, setState, real]
10+
*/
11+
export function useDebouncedState<T> (initial: T, timeoutMs = DEFAULT_TIMEOUT_MS): [state: T, setState: React.Dispatch<React.SetStateAction<T>>, real: T] {
12+
const [debounced, setDebounced] = useState(initial)
13+
const [real, setReal] = useState(initial)
14+
15+
useEffect(() => {
16+
const timeout = setTimeout(() => {
17+
setDebounced(real)
18+
}, timeoutMs)
19+
20+
return () => clearTimeout(timeout)
21+
}, [real, timeoutMs])
22+
23+
return [debounced, setReal, real]
24+
}

index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,7 @@ export {
77
StatefulSet,
88
useSet
99
} from './hooks/use-set'
10+
11+
export {
12+
useDebouncedState
13+
} from './hooks/use-debounced-state'

0 commit comments

Comments
 (0)