|
1
|
import debounce from "lodash.debounce" |
|
2
|
import { useCallback, useEffect, useState } from "react" |
|
3
|
|
|
4
|
/** |
|
5
|
* Hook for debouncing search input |
|
6
|
* @returns searchValue, onSearchValueChange, query |
|
7
|
*/ |
|
8
|
export const useDebouncedSearch = () => { |
|
9
|
const [searchValue, onSearchValueChange] = useState("") |
|
10
|
const [debouncedQuery, setDebouncedQuery] = useState("") |
|
11
|
|
|
12
|
// eslint-disable-next-line react-hooks/exhaustive-deps |
|
13
|
const debouncedUpdate = useCallback( |
|
14
|
debounce((query: string) => setDebouncedQuery(query), 300), |
|
15
|
[] |
|
16
|
) |
|
17
|
|
|
18
|
useEffect(() => { |
|
19
|
debouncedUpdate(searchValue) |
|
20
|
|
|
21
|
return () => debouncedUpdate.cancel() |
|
22
|
}, [searchValue, debouncedUpdate]) |
|
23
|
|
|
24
|
return { |
|
25
|
searchValue, |
|
26
|
onSearchValueChange, |
|
27
|
query: debouncedQuery, |
|
28
|
} |
|
29
|
} |