Skip to content

useDebounce

Delay execution of a callback update until a defined wait period.

The useDebounce hook is helpful when you want to delay the execution of a callback until a given wait period (ms).

This is helpful in scenarios when you want to make an API requests based on user input like search, or when you find to delayed executing rapid changes like scroll events etc.

useDebounce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

Scroll Percent: 0%

Scroll on the list of tems above and find the scroll percentage.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { useDebounce } from '@abhushanaj/react-hooks';
function App() {
const [debouncedOnScroll, { cancel }] = useDebounce((e) => {
console.log('Scroll Event Triggred', e);
}, 200);
return (
<div style={{ minHeight: '400vh' }} onScroll={debouncedOnScroll}>
Scrollable content
</div>
);
}
export default App;

Properties

  1. Passing negative wait (ms) value, will throw an error. Only values greater than or equal to zero are allowed.

API Reference

Parameters

ParameterTypeDescriptionDefault
callback(...args: Array<unknown>)=>voidThe callback which needs to be debounced.N/A
waitnumberThe wait time in milliseconds.N/A

Return Value

The return value is of the shape [debouncedFn, debounceFnControls].

ParameterTypeDescriptionDefault
debouncedFn(...args: Array<unknown>)=>voidThe debounced callback over wait(ms) time period.N/A
debounceFnControlsDebounceFnControlsControls for the debounced function.N/A

Types Reference

1. DebounceFnControls

ParameterTypeDescriptionDefault
cancel()=>voidCancels any pending invocations for the debounced callback function.N/A