@usefy/use-debounce 0.0.8 → 0.0.10

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.
Files changed (2) hide show
  1. package/README.md +452 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,452 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/geon0529/usefy/master/assets/logo.png" alt="usefy logo" width="120" />
3
+ </p>
4
+
5
+ <h1 align="center">@usefy/use-debounce</h1>
6
+
7
+ <p align="center">
8
+ <strong>A feature-rich React hook for debouncing values with leading/trailing edge and maxWait support</strong>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@usefy/use-debounce">
13
+ <img src="https://img.shields.io/npm/v/@usefy/use-debounce.svg?style=flat-square&color=007acc" alt="npm version" />
14
+ </a>
15
+ <a href="https://www.npmjs.com/package/@usefy/use-debounce">
16
+ <img src="https://img.shields.io/npm/dm/@usefy/use-debounce.svg?style=flat-square&color=007acc" alt="npm downloads" />
17
+ </a>
18
+ <a href="https://bundlephobia.com/package/@usefy/use-debounce">
19
+ <img src="https://img.shields.io/bundlephobia/minzip/@usefy/use-debounce?style=flat-square&color=007acc" alt="bundle size" />
20
+ </a>
21
+ <a href="https://github.com/geon0529/usefy/blob/master/LICENSE">
22
+ <img src="https://img.shields.io/npm/l/@usefy/use-debounce.svg?style=flat-square&color=007acc" alt="license" />
23
+ </a>
24
+ </p>
25
+
26
+ <p align="center">
27
+ <a href="#installation">Installation</a> •
28
+ <a href="#quick-start">Quick Start</a> •
29
+ <a href="#api-reference">API Reference</a> •
30
+ <a href="#examples">Examples</a> •
31
+ <a href="#license">License</a>
32
+ </p>
33
+
34
+ ---
35
+
36
+ ## Overview
37
+
38
+ `@usefy/use-debounce` is a powerful React hook for debouncing values with advanced options like leading edge, trailing edge, and maximum wait time. Perfect for search inputs, form validation, API calls, and any scenario where you need to limit the rate of value updates.
39
+
40
+ **Part of the [@usefy](https://www.npmjs.com/org/usefy) ecosystem** — a collection of production-ready React hooks designed for modern applications.
41
+
42
+ ### Why use-debounce?
43
+
44
+ - **Zero Dependencies** — Pure React implementation with no external dependencies
45
+ - **TypeScript First** — Full type safety with generics and exported interfaces
46
+ - **Flexible Options** — Leading edge, trailing edge, and maxWait support
47
+ - **SSR Compatible** — Works seamlessly with Next.js, Remix, and other SSR frameworks
48
+ - **Lightweight** — Minimal bundle footprint (~400B minified + gzipped)
49
+ - **Well Tested** — Comprehensive test coverage with Vitest
50
+
51
+ ---
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ # npm
57
+ npm install @usefy/use-debounce
58
+
59
+ # yarn
60
+ yarn add @usefy/use-debounce
61
+
62
+ # pnpm
63
+ pnpm add @usefy/use-debounce
64
+ ```
65
+
66
+ ### Peer Dependencies
67
+
68
+ This package requires React 18 or 19:
69
+
70
+ ```json
71
+ {
72
+ "peerDependencies": {
73
+ "react": "^18.0.0 || ^19.0.0"
74
+ }
75
+ }
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Quick Start
81
+
82
+ ```tsx
83
+ import { useDebounce } from '@usefy/use-debounce';
84
+
85
+ function SearchInput() {
86
+ const [query, setQuery] = useState('');
87
+ const debouncedQuery = useDebounce(query, 300);
88
+
89
+ useEffect(() => {
90
+ if (debouncedQuery) {
91
+ searchAPI(debouncedQuery);
92
+ }
93
+ }, [debouncedQuery]);
94
+
95
+ return (
96
+ <input
97
+ type="text"
98
+ value={query}
99
+ onChange={(e) => setQuery(e.target.value)}
100
+ placeholder="Search..."
101
+ />
102
+ );
103
+ }
104
+ ```
105
+
106
+ ---
107
+
108
+ ## API Reference
109
+
110
+ ### `useDebounce<T>(value, delay?, options?)`
111
+
112
+ A hook that returns a debounced version of the provided value.
113
+
114
+ #### Parameters
115
+
116
+ | Parameter | Type | Default | Description |
117
+ |-----------|------|---------|-------------|
118
+ | `value` | `T` | — | The value to debounce |
119
+ | `delay` | `number` | `500` | The debounce delay in milliseconds |
120
+ | `options` | `UseDebounceOptions` | `{}` | Additional configuration options |
121
+
122
+ #### Options
123
+
124
+ | Option | Type | Default | Description |
125
+ |--------|------|---------|-------------|
126
+ | `leading` | `boolean` | `false` | Update on the leading edge (first call) |
127
+ | `trailing` | `boolean` | `true` | Update on the trailing edge (after delay) |
128
+ | `maxWait` | `number` | — | Maximum time to wait before forcing an update |
129
+
130
+ #### Returns
131
+
132
+ | Type | Description |
133
+ |------|-------------|
134
+ | `T` | The debounced value |
135
+
136
+ ---
137
+
138
+ ## Examples
139
+
140
+ ### Basic Search Input
141
+
142
+ ```tsx
143
+ import { useDebounce } from '@usefy/use-debounce';
144
+
145
+ function SearchInput() {
146
+ const [query, setQuery] = useState('');
147
+ const debouncedQuery = useDebounce(query, 300);
148
+ const [results, setResults] = useState([]);
149
+
150
+ useEffect(() => {
151
+ async function search() {
152
+ if (!debouncedQuery.trim()) {
153
+ setResults([]);
154
+ return;
155
+ }
156
+ const data = await fetch(`/api/search?q=${debouncedQuery}`);
157
+ setResults(await data.json());
158
+ }
159
+ search();
160
+ }, [debouncedQuery]);
161
+
162
+ return (
163
+ <div>
164
+ <input
165
+ value={query}
166
+ onChange={(e) => setQuery(e.target.value)}
167
+ placeholder="Type to search..."
168
+ />
169
+ <ul>
170
+ {results.map((result) => (
171
+ <li key={result.id}>{result.name}</li>
172
+ ))}
173
+ </ul>
174
+ </div>
175
+ );
176
+ }
177
+ ```
178
+
179
+ ### With Leading Edge (Instant First Update)
180
+
181
+ ```tsx
182
+ import { useDebounce } from '@usefy/use-debounce';
183
+
184
+ function FilterPanel() {
185
+ const [filters, setFilters] = useState({ category: 'all', price: 0 });
186
+
187
+ // Update immediately on first change, then debounce subsequent changes
188
+ const debouncedFilters = useDebounce(filters, 500, { leading: true });
189
+
190
+ useEffect(() => {
191
+ applyFilters(debouncedFilters);
192
+ }, [debouncedFilters]);
193
+
194
+ return (
195
+ <div>
196
+ <select
197
+ value={filters.category}
198
+ onChange={(e) => setFilters(f => ({ ...f, category: e.target.value }))}
199
+ >
200
+ <option value="all">All</option>
201
+ <option value="electronics">Electronics</option>
202
+ <option value="clothing">Clothing</option>
203
+ </select>
204
+ <input
205
+ type="range"
206
+ value={filters.price}
207
+ onChange={(e) => setFilters(f => ({ ...f, price: +e.target.value }))}
208
+ />
209
+ </div>
210
+ );
211
+ }
212
+ ```
213
+
214
+ ### With maxWait (Guaranteed Updates)
215
+
216
+ ```tsx
217
+ import { useDebounce } from '@usefy/use-debounce';
218
+
219
+ function AutoSaveEditor() {
220
+ const [content, setContent] = useState('');
221
+
222
+ // Debounce for 1 second, but guarantee save every 5 seconds during continuous typing
223
+ const debouncedContent = useDebounce(content, 1000, { maxWait: 5000 });
224
+
225
+ useEffect(() => {
226
+ if (debouncedContent) {
227
+ saveToServer(debouncedContent);
228
+ }
229
+ }, [debouncedContent]);
230
+
231
+ return (
232
+ <textarea
233
+ value={content}
234
+ onChange={(e) => setContent(e.target.value)}
235
+ placeholder="Start typing... (auto-saves)"
236
+ />
237
+ );
238
+ }
239
+ ```
240
+
241
+ ### Form Validation
242
+
243
+ ```tsx
244
+ import { useDebounce } from '@usefy/use-debounce';
245
+
246
+ function RegistrationForm() {
247
+ const [username, setUsername] = useState('');
248
+ const [error, setError] = useState('');
249
+ const debouncedUsername = useDebounce(username, 500);
250
+
251
+ useEffect(() => {
252
+ async function checkAvailability() {
253
+ if (debouncedUsername.length < 3) {
254
+ setError('Username must be at least 3 characters');
255
+ return;
256
+ }
257
+ const response = await fetch(`/api/check-username?u=${debouncedUsername}`);
258
+ const { available } = await response.json();
259
+ setError(available ? '' : 'Username is already taken');
260
+ }
261
+
262
+ if (debouncedUsername) {
263
+ checkAvailability();
264
+ }
265
+ }, [debouncedUsername]);
266
+
267
+ return (
268
+ <div>
269
+ <input
270
+ value={username}
271
+ onChange={(e) => setUsername(e.target.value)}
272
+ placeholder="Choose a username"
273
+ />
274
+ {error && <span className="error">{error}</span>}
275
+ </div>
276
+ );
277
+ }
278
+ ```
279
+
280
+ ### Debouncing Object Values
281
+
282
+ ```tsx
283
+ import { useDebounce } from '@usefy/use-debounce';
284
+
285
+ function FilteredTable() {
286
+ const [filters, setFilters] = useState({
287
+ search: '',
288
+ status: 'all',
289
+ sortBy: 'date',
290
+ });
291
+
292
+ const debouncedFilters = useDebounce(filters, 300);
293
+
294
+ useEffect(() => {
295
+ fetchTableData(debouncedFilters);
296
+ }, [debouncedFilters]);
297
+
298
+ return (
299
+ <div>
300
+ <input
301
+ value={filters.search}
302
+ onChange={(e) => setFilters(f => ({ ...f, search: e.target.value }))}
303
+ placeholder="Search..."
304
+ />
305
+ <select
306
+ value={filters.status}
307
+ onChange={(e) => setFilters(f => ({ ...f, status: e.target.value }))}
308
+ >
309
+ <option value="all">All</option>
310
+ <option value="active">Active</option>
311
+ <option value="inactive">Inactive</option>
312
+ </select>
313
+ </div>
314
+ );
315
+ }
316
+ ```
317
+
318
+ ---
319
+
320
+ ## TypeScript
321
+
322
+ This hook is written in TypeScript with full generic support.
323
+
324
+ ```tsx
325
+ import { useDebounce, type UseDebounceOptions } from '@usefy/use-debounce';
326
+
327
+ // Generic type inference
328
+ const debouncedString = useDebounce('hello', 300); // string
329
+ const debouncedNumber = useDebounce(42, 300); // number
330
+ const debouncedObject = useDebounce({ x: 1 }, 300); // { x: number }
331
+
332
+ // Explicit generic type
333
+ interface Filters {
334
+ search: string;
335
+ category: string;
336
+ }
337
+ const debouncedFilters = useDebounce<Filters>(filters, 300);
338
+ ```
339
+
340
+ ---
341
+
342
+ ## Testing
343
+
344
+ This package maintains comprehensive test coverage to ensure reliability and stability.
345
+
346
+ ### Test Coverage
347
+
348
+ | Category | Tests | Coverage |
349
+ |----------|-------|----------|
350
+ | Initialization | 6 | 100% |
351
+ | Basic Debouncing | 6 | 100% |
352
+ | Leading Edge | 5 | 100% |
353
+ | Trailing Edge | 3 | 100% |
354
+ | maxWait Option | 5 | 100% |
355
+ | Option Changes | 3 | 100% |
356
+ | Type Preservation | 5 | 100% |
357
+ | Cleanup | 2 | 100% |
358
+ | Edge Cases | 6 | 100% |
359
+ | **Total** | **41** | **93.02%** |
360
+
361
+ ### Test Categories
362
+
363
+ <details>
364
+ <summary><strong>Initialization Tests</strong></summary>
365
+
366
+ - Initialize with initial value
367
+ - Initialize with different types (string, number, boolean, object, array)
368
+ - Use default delay of 500ms
369
+
370
+ </details>
371
+
372
+ <details>
373
+ <summary><strong>Leading/Trailing Edge Tests</strong></summary>
374
+
375
+ - Update immediately with leading: true
376
+ - Do not update immediately with leading: false (default)
377
+ - Update on trailing edge with trailing: true (default)
378
+ - No update with trailing: false
379
+ - Combined leading and trailing options
380
+
381
+ </details>
382
+
383
+ <details>
384
+ <summary><strong>maxWait Tests</strong></summary>
385
+
386
+ - Force update after maxWait even with continuous changes
387
+ - Respect maxWait when delay is longer
388
+ - Work correctly with both leading and maxWait
389
+
390
+ </details>
391
+
392
+ ### Running Tests
393
+
394
+ ```bash
395
+ # Run all tests
396
+ pnpm test
397
+
398
+ # Run tests in watch mode
399
+ pnpm test:watch
400
+
401
+ # Run tests with coverage report
402
+ pnpm test --coverage
403
+ ```
404
+
405
+ ---
406
+
407
+ ## Related Packages
408
+
409
+ Explore other hooks in the **@usefy** collection:
410
+
411
+ | Package | Description |
412
+ |---------|-------------|
413
+ | [@usefy/use-debounce-callback](https://www.npmjs.com/package/@usefy/use-debounce-callback) | Debounced callbacks with cancel/flush |
414
+ | [@usefy/use-throttle](https://www.npmjs.com/package/@usefy/use-throttle) | Value throttling |
415
+ | [@usefy/use-throttle-callback](https://www.npmjs.com/package/@usefy/use-throttle-callback) | Throttled callbacks |
416
+ | [@usefy/use-toggle](https://www.npmjs.com/package/@usefy/use-toggle) | Boolean state management |
417
+ | [@usefy/use-counter](https://www.npmjs.com/package/@usefy/use-counter) | Counter state management |
418
+ | [@usefy/use-click-any-where](https://www.npmjs.com/package/@usefy/use-click-any-where) | Global click detection |
419
+
420
+ ---
421
+
422
+ ## Contributing
423
+
424
+ We welcome contributions! Please see our [Contributing Guide](https://github.com/geon0529/usefy/blob/master/CONTRIBUTING.md) for details.
425
+
426
+ ```bash
427
+ # Clone the repository
428
+ git clone https://github.com/geon0529/usefy.git
429
+
430
+ # Install dependencies
431
+ pnpm install
432
+
433
+ # Run tests
434
+ pnpm test
435
+
436
+ # Build
437
+ pnpm build
438
+ ```
439
+
440
+ ---
441
+
442
+ ## License
443
+
444
+ MIT © [mirunamu](https://github.com/geon0529)
445
+
446
+ This package is part of the [usefy](https://github.com/geon0529/usefy) monorepo.
447
+
448
+ ---
449
+
450
+ <p align="center">
451
+ <sub>Built with care by the usefy team</sub>
452
+ </p>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usefy/use-debounce",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "A React hook for value debouncing with leading/trailing edge and maxWait options",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",