react-hook-toolkit 3.0.4 → 4.0.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/README.md +3 -786
- package/dist/chunk1516/chunk0021.d.ts +1 -1
- package/dist/chunk1516/chunk0021.js +10 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,795 +24,12 @@ pnpm add react-hook-toolkit
|
|
|
24
24
|
| Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
|
|
25
25
|
|
|
26
26
|
|
|
27
|
-
###
|
|
28
|
-
Here's the properly structured documentation with clear purpose explanations:
|
|
27
|
+
### **Documentation**
|
|
29
28
|
|
|
30
|
-
|
|
29
|
+
Comprehensive documentation with step-by-step guides, practical examples, and easy-to-follow explanations to help you quickly understand and use all custom hooks effectively.
|
|
31
30
|
|
|
32
|
-
|
|
33
|
-
Provides comprehensive browser control and environment detection with a unified API for navigation, window management, and system interactions.
|
|
31
|
+
👉 https://react-hook-toolkit.netlify.app
|
|
34
32
|
|
|
35
|
-
```ts
|
|
36
|
-
const {
|
|
37
|
-
goBack,
|
|
38
|
-
goForward,
|
|
39
|
-
reload,
|
|
40
|
-
navigateTo,
|
|
41
|
-
clearBrowserData,
|
|
42
|
-
historyState,
|
|
43
|
-
isOnline,
|
|
44
|
-
copyCurrentUrl,
|
|
45
|
-
openNewTab,
|
|
46
|
-
isFullscreen,
|
|
47
|
-
isShareSupported,
|
|
48
|
-
closeCurrentTab
|
|
49
|
-
} = useBrowser();
|
|
50
|
-
```
|
|
51
|
-
---
|
|
52
|
-
|
|
53
|
-
📌 **useRouter**
|
|
54
|
-
Keeps track of the current URL path and query parameters, and allows navigation by updating the browser URL. Useful for lightweight routing in apps without full routing libraries.
|
|
55
|
-
|
|
56
|
-
```ts
|
|
57
|
-
const { pathname, searchParams, navigate } = useRouter();
|
|
58
|
-
|
|
59
|
-
console.log(pathname); // "/dashboard"
|
|
60
|
-
|
|
61
|
-
console.log(searchParams.get("tab")); // "home"
|
|
62
|
-
|
|
63
|
-
navigate("/dashboard?tab=home");
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
---
|
|
67
|
-
|
|
68
|
-
📌 **useNavigationState**
|
|
69
|
-
Combines the functionality of `useRouter` and React Router’s `useNavigate` + `useLocation`. Tracks `pathname`, `searchParams`, and `state` (from pushState), and allows navigation while passing custom state.
|
|
70
|
-
|
|
71
|
-
```ts
|
|
72
|
-
const { pathname, searchParams, state, navigate } = useNavigationState();
|
|
73
|
-
|
|
74
|
-
console.log(pathname); // "/dashboard"
|
|
75
|
-
|
|
76
|
-
console.log(searchParams.get("tab")); // "home"
|
|
77
|
-
|
|
78
|
-
console.log(state?.id); // 34
|
|
79
|
-
|
|
80
|
-
navigate("/dashboard", { state: { id: 34 } });
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
---
|
|
84
|
-
|
|
85
|
-
📌 **useRequest**
|
|
86
|
-
Provides an easy way to fetch data with hooks, managing loading, data, and error states.
|
|
87
|
-
|
|
88
|
-
```ts
|
|
89
|
-
const { data, loading, error } = useRequest('/api/data');
|
|
90
|
-
```
|
|
91
|
-
---
|
|
92
|
-
📌 **useRequestRetry**
|
|
93
|
-
Performs an HTTP request with retry logic, retrying a specified number of times upon failure before returning an error.
|
|
94
|
-
|
|
95
|
-
```ts
|
|
96
|
-
const { data, loading, error } = useRequestRetry('/api/user', { method: 'GET' }, 3);
|
|
97
|
-
```
|
|
98
|
-
---
|
|
99
|
-
📌 **useAsync**
|
|
100
|
-
Handles the state of an asynchronous function, including loading, success, and error states, with the ability to trigger the execution of the async operation.
|
|
101
|
-
|
|
102
|
-
```ts
|
|
103
|
-
const { execute, status, value, error } = useAsync(fetchUser);
|
|
104
|
-
|
|
105
|
-
execute(); // ➝ runs the async function
|
|
106
|
-
```
|
|
107
|
-
---
|
|
108
|
-
📌 **useDebounce**
|
|
109
|
-
Delays updating the state until after a specified delay, useful for preventing frequent updates (e.g., handling user input).
|
|
110
|
-
|
|
111
|
-
```ts
|
|
112
|
-
const debouncedSearch = useDebounce(searchText, 500);
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
---
|
|
116
|
-
📌 **useDebouncedCallback**
|
|
117
|
-
Delays the execution of a callback function until after a specified delay, resetting the delay on each call to prevent frequent execution.
|
|
118
|
-
|
|
119
|
-
```ts
|
|
120
|
-
const debounced = useDebouncedCallback(() => search(input), 300);
|
|
121
|
-
|
|
122
|
-
input.onChange = debounced;
|
|
123
|
-
```
|
|
124
|
-
---
|
|
125
|
-
📌 **useDebouncedValue**
|
|
126
|
-
Returns a debounced version of a value.
|
|
127
|
-
|
|
128
|
-
```ts
|
|
129
|
-
const debouncedValue = useDebouncedValue(value, 300);
|
|
130
|
-
```
|
|
131
|
-
---
|
|
132
|
-
📌 **useThrottle**
|
|
133
|
-
Limits how often a value updates within a given time interval, useful for performance optimization.
|
|
134
|
-
|
|
135
|
-
```ts
|
|
136
|
-
const throttledScroll = useThrottle(scrollValue, 300);
|
|
137
|
-
```
|
|
138
|
-
|
|
139
|
-
---
|
|
140
|
-
📌 **useDelay**
|
|
141
|
-
Delays the update of a value for a specified amount of time before reflecting it in the state.
|
|
142
|
-
|
|
143
|
-
```ts
|
|
144
|
-
const delayedValue = useDelay(value, 500);
|
|
145
|
-
```
|
|
146
|
-
---
|
|
147
|
-
📌 **useTimer**
|
|
148
|
-
Starts a countdown timer that updates the time every second, returning the current time and any errors.
|
|
149
|
-
|
|
150
|
-
```ts
|
|
151
|
-
const { time, error } = useTimer(60); // starts from 60 and counts down
|
|
152
|
-
```
|
|
153
|
-
---
|
|
154
|
-
📌 **useInterval**
|
|
155
|
-
Runs a callback function at a specified time interval and clears it when the delay is null or the component unmounts.
|
|
156
|
-
|
|
157
|
-
```ts
|
|
158
|
-
useInterval(() => {
|
|
159
|
-
console.log('Tick');
|
|
160
|
-
}, 1000);
|
|
161
|
-
```
|
|
162
|
-
---
|
|
163
|
-
📌 **useTimeout**
|
|
164
|
-
Executes a function after a specified delay and cleans up automatically when dependencies change.
|
|
165
|
-
|
|
166
|
-
```ts
|
|
167
|
-
useTimeout(() => {
|
|
168
|
-
console.log('Time\'s up!');
|
|
169
|
-
}, 2000);
|
|
170
|
-
```
|
|
171
|
-
|
|
172
|
-
---
|
|
173
|
-
|
|
174
|
-
📌 **useForm**
|
|
175
|
-
Manages form state, handles input changes, and performs validation using provided validators.
|
|
176
|
-
|
|
177
|
-
```ts
|
|
178
|
-
const { values, errors, handleChange, validate } = useForm({ name: '', email: '' });
|
|
179
|
-
|
|
180
|
-
handleChange('name', 'John');
|
|
181
|
-
|
|
182
|
-
validate({
|
|
183
|
-
name: (val) => (!val ? 'Required' : null),
|
|
184
|
-
email: (val) => (!val.includes('@') ? 'Invalid email' : null),
|
|
185
|
-
});
|
|
186
|
-
```
|
|
187
|
-
---
|
|
188
|
-
📌 **useFormSubmit**
|
|
189
|
-
Handles form submission with loading/error states and success callbacks.
|
|
190
|
-
|
|
191
|
-
```ts
|
|
192
|
-
const { submit, isLoading, error } = useFormSubmit(apiCall, {
|
|
193
|
-
onSuccess: (data) => console.log('Saved!', data)
|
|
194
|
-
});
|
|
195
|
-
|
|
196
|
-
// Example
|
|
197
|
-
submit(formData);
|
|
198
|
-
```
|
|
199
|
-
---
|
|
200
|
-
📌 **useSmartForm**
|
|
201
|
-
Complete form management with validation, submission, and state handling.
|
|
202
|
-
|
|
203
|
-
```ts
|
|
204
|
-
const { register, handleSubmit, errors } = useSmartForm({
|
|
205
|
-
initialValues,
|
|
206
|
-
validationSchema,
|
|
207
|
-
onSubmit: (data) => console.log(data)
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
// Example
|
|
211
|
-
<input {...register('email') />
|
|
212
|
-
<button onClick={handleSubmit}>Save</button>
|
|
213
|
-
```
|
|
214
|
-
---
|
|
215
|
-
📌 **useCrossFieldValidation**
|
|
216
|
-
Handles complex validation rules that depend on multiple fields.
|
|
217
|
-
|
|
218
|
-
```ts
|
|
219
|
-
const { errors, validate } = useCrossFieldValidation({
|
|
220
|
-
rules: {
|
|
221
|
-
password: (val, { confirmPassword }) => val === confirmPassword,
|
|
222
|
-
},
|
|
223
|
-
initialValues
|
|
224
|
-
});
|
|
225
|
-
|
|
226
|
-
// Example
|
|
227
|
-
validate('password', 'secret123', { confirmPassword: 'secret123' });
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
---
|
|
231
|
-
|
|
232
|
-
📌 **useFieldArray**
|
|
233
|
-
Manages dynamic arrays of form fields with add/remove/reorder operations.
|
|
234
|
-
|
|
235
|
-
```ts
|
|
236
|
-
const { fields, append, remove, move } = useFieldArray(initialItems);
|
|
237
|
-
|
|
238
|
-
// Example
|
|
239
|
-
append({ name: '', email: '' });
|
|
240
|
-
remove(0); // Remove first item
|
|
241
|
-
move(1, 0); // Move second item to first position
|
|
242
|
-
```
|
|
243
|
-
---
|
|
244
|
-
📌 **useFormWizard**
|
|
245
|
-
Manages multi-step forms with navigation between steps.
|
|
246
|
-
|
|
247
|
-
```ts
|
|
248
|
-
const { currentStep, next, prev, goto } = useFormWizard(steps.length);
|
|
249
|
-
|
|
250
|
-
// Example
|
|
251
|
-
next(); // Move to next step
|
|
252
|
-
goto(3); // Jump to step 4
|
|
253
|
-
```
|
|
254
|
-
|
|
255
|
-
---
|
|
256
|
-
📌 **usePersistedForm**
|
|
257
|
-
Automatically persists form state to localStorage/sessionStorage and restores it on page reload.
|
|
258
|
-
|
|
259
|
-
```ts
|
|
260
|
-
const { values, setField, reset } = usePersistedForm('form-key', initialValues);
|
|
261
|
-
|
|
262
|
-
// Example
|
|
263
|
-
setField('username', 'john_doe'); // Auto-saves to storage
|
|
264
|
-
reset(); // Clears storage
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
---
|
|
269
|
-
|
|
270
|
-
📌 **useEventListener**
|
|
271
|
-
Listens for a specified event on an element or window, and triggers the handler function when the event is fired. It ensures proper cleanup when the component is unmounted.
|
|
272
|
-
|
|
273
|
-
```ts
|
|
274
|
-
useEventListener('resize', (e) => {
|
|
275
|
-
console.log('Window resized');
|
|
276
|
-
});
|
|
277
|
-
```
|
|
278
|
-
---
|
|
279
|
-
📌 **useEventListeners**
|
|
280
|
-
Simplifies adding/removing event listeners.
|
|
281
|
-
|
|
282
|
-
```ts
|
|
283
|
-
useEventListeners({
|
|
284
|
-
click: handleClick,
|
|
285
|
-
resize: handleResize
|
|
286
|
-
});
|
|
287
|
-
|
|
288
|
-
// Example
|
|
289
|
-
useEventListeners({
|
|
290
|
-
keydown: (e) => console.log(e.key)
|
|
291
|
-
});
|
|
292
|
-
```
|
|
293
|
-
---
|
|
294
|
-
📌 **useKeyPress**
|
|
295
|
-
Detects whether a specific key is being pressed or released.
|
|
296
|
-
|
|
297
|
-
```ts
|
|
298
|
-
const isEnterPressed = useKeyPress('Enter');
|
|
299
|
-
```
|
|
300
|
-
---
|
|
301
|
-
📌 **useLongPress**
|
|
302
|
-
Detects long press gestures.
|
|
303
|
-
|
|
304
|
-
```ts
|
|
305
|
-
const handlers = useLongPress(() => console.log('Long pressed!'), {
|
|
306
|
-
threshold: 1000
|
|
307
|
-
});
|
|
308
|
-
|
|
309
|
-
// Example
|
|
310
|
-
<button {...handlers}>Hold me</button>
|
|
311
|
-
```
|
|
312
|
-
---
|
|
313
|
-
📌 **useTouch**
|
|
314
|
-
Tracks touch events on a given DOM element, returning the touch positions for `touchstart`, `touchmove`, and `touchend`.
|
|
315
|
-
|
|
316
|
-
```ts
|
|
317
|
-
const ref = useRef(null);
|
|
318
|
-
const {
|
|
319
|
-
touchStart,
|
|
320
|
-
touchMove,
|
|
321
|
-
touchEnd
|
|
322
|
-
} = useTouch(ref);
|
|
323
|
-
|
|
324
|
-
<div ref={ref}>Swipe here</div>
|
|
325
|
-
```
|
|
326
|
-
---
|
|
327
|
-
📌 **useIdle**
|
|
328
|
-
Detects when user becomes inactive.
|
|
329
|
-
|
|
330
|
-
```ts
|
|
331
|
-
const isIdle = useIdle(30000); // 30s timeout
|
|
332
|
-
|
|
333
|
-
// Example
|
|
334
|
-
{isIdle && <ScreenSaver />}
|
|
335
|
-
```
|
|
336
|
-
---
|
|
337
|
-
📌 **useDragReorder**
|
|
338
|
-
Enables drag-and-drop reordering of lists.
|
|
339
|
-
|
|
340
|
-
```ts
|
|
341
|
-
const { items, dragStart, dragOver, drop } = useDragReorder(initialItems);
|
|
342
|
-
|
|
343
|
-
// Example
|
|
344
|
-
<div
|
|
345
|
-
draggable
|
|
346
|
-
onDragStart={() => dragStart(index)}
|
|
347
|
-
onDragOver={() => dragOver(index)}
|
|
348
|
-
onDrop={drop}
|
|
349
|
-
/>
|
|
350
|
-
```
|
|
351
|
-
|
|
352
|
-
---
|
|
353
|
-
|
|
354
|
-
📌 **useToggle**
|
|
355
|
-
A simple boolean toggle hook that returns a state and a function to toggle its value.
|
|
356
|
-
|
|
357
|
-
```ts
|
|
358
|
-
const [isOpen, toggle] = useToggle(false);
|
|
359
|
-
```
|
|
360
|
-
---
|
|
361
|
-
📌 **useArray**
|
|
362
|
-
Provides an array state with helper functions to manipulate it, including setting, adding, removing by index, and clearing elements.
|
|
363
|
-
|
|
364
|
-
```ts
|
|
365
|
-
const { array, set, push, removeByIndex, clear } = useArray([1, 2, 3]);
|
|
366
|
-
|
|
367
|
-
push(4); // ➝ [1, 2, 3, 4]
|
|
368
|
-
removeByIndex(1); // ➝ [1, 3, 4]
|
|
369
|
-
clear(); // ➝ []
|
|
370
|
-
```
|
|
371
|
-
---
|
|
372
|
-
📌 **useStepper**
|
|
373
|
-
Manages step-based navigation by keeping track of the current step index and providing functions to move forward, backward, and reset.
|
|
374
|
-
|
|
375
|
-
```ts
|
|
376
|
-
const { activeStep, handleNext, handleBack, handleReset, isFirstStep, isLastStep } = useStepper(5);
|
|
377
|
-
|
|
378
|
-
handleNext(); // ➝ advances step
|
|
379
|
-
handleBack(); // ➝ goes back
|
|
380
|
-
handleReset(); // ➝ step 0
|
|
381
|
-
```
|
|
382
|
-
|
|
383
|
-
📌 **useDrawer**
|
|
384
|
-
Provides global drawer state and controls to open/close the drawer and manage the current selected main menu, including support for button-triggered toggling.
|
|
385
|
-
|
|
386
|
-
```ts
|
|
387
|
-
const {
|
|
388
|
-
drawerOpen,
|
|
389
|
-
openDrawer,
|
|
390
|
-
closeDrawer,
|
|
391
|
-
openDrawerInButton,
|
|
392
|
-
closeDrawerInButton,
|
|
393
|
-
currentMainMenu,
|
|
394
|
-
setCurrentMainMenu,
|
|
395
|
-
} = useContext();
|
|
396
|
-
```
|
|
397
|
-
|
|
398
|
-
---
|
|
399
|
-
📌 **useUndo**
|
|
400
|
-
Provides undo/redo functionality for state changes.
|
|
401
|
-
|
|
402
|
-
```ts
|
|
403
|
-
const { state, setState, undo, redo } = useUndo(initialState);
|
|
404
|
-
|
|
405
|
-
// Example
|
|
406
|
-
setState({ items: [...] });
|
|
407
|
-
undo(); // Reverts to previous state
|
|
408
|
-
```
|
|
409
|
-
---
|
|
410
|
-
📌 **useGenericReducer**
|
|
411
|
-
A custom reducer function that takes an `initialState` and an object of actions, returning a new state based on the action type.
|
|
412
|
-
|
|
413
|
-
```ts
|
|
414
|
-
const reducer = useGenericReducer(initialState, {
|
|
415
|
-
increment: (state) => ({ count: state.count + 1 }),
|
|
416
|
-
});
|
|
417
|
-
const [state, dispatch] = useReducer(reducer, initialState);
|
|
418
|
-
```
|
|
419
|
-
---
|
|
420
|
-
📌 **useIsMounted**
|
|
421
|
-
Tracks whether the component is mounted or unmounted, returning a boolean value indicating the component's mount status.
|
|
422
|
-
|
|
423
|
-
```ts
|
|
424
|
-
const isMounted = useIsMounted();
|
|
425
|
-
```
|
|
426
|
-
---
|
|
427
|
-
📌 **useIsFirstRender**
|
|
428
|
-
Returns true only on component's first render.
|
|
429
|
-
|
|
430
|
-
```ts
|
|
431
|
-
const isFirst = useIsFirstRender();
|
|
432
|
-
|
|
433
|
-
// Example
|
|
434
|
-
useEffect(() => {
|
|
435
|
-
if (!isFirst) console.log('Updated!');
|
|
436
|
-
}, [deps]);
|
|
437
|
-
```
|
|
438
|
-
---
|
|
439
|
-
📌 **usePrevious**
|
|
440
|
-
Tracks the previous value of a state or prop.
|
|
441
|
-
|
|
442
|
-
```ts
|
|
443
|
-
const previousValue = usePrevious(currentValue);
|
|
444
|
-
```
|
|
445
|
-
---
|
|
446
|
-
📌 **useUpdateEffect**
|
|
447
|
-
Executes a side effect on updates after the initial render, skipping the effect during the first render to avoid unnecessary executions.
|
|
448
|
-
|
|
449
|
-
```ts
|
|
450
|
-
useUpdateEffect(() => {
|
|
451
|
-
console.log("This runs only on updates.");
|
|
452
|
-
}, [value]);
|
|
453
|
-
```
|
|
454
|
-
---
|
|
455
|
-
|
|
456
|
-
📌 **useList**
|
|
457
|
-
Manages array state with utility methods.
|
|
458
|
-
|
|
459
|
-
```ts
|
|
460
|
-
const { list, push, remove, update } = useList(initialItems);
|
|
461
|
-
|
|
462
|
-
// Example
|
|
463
|
-
push(newItem);
|
|
464
|
-
remove(0); // Remove first item
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
---
|
|
468
|
-
|
|
469
|
-
📌 **useLocalStorage**
|
|
470
|
-
A hook to persist state in `localStorage`. It initializes state from `localStorage` and updates it whenever the value changes.
|
|
471
|
-
|
|
472
|
-
```ts
|
|
473
|
-
const [token, setToken] = useLocalStorage('authToken', '');
|
|
474
|
-
```
|
|
475
|
-
---
|
|
476
|
-
📌 **useSessionStorage**
|
|
477
|
-
Stores and retrieves data from the `sessionStorage` API, persisting the data during the session. It provides a getter and setter for session-based data.
|
|
478
|
-
|
|
479
|
-
```ts
|
|
480
|
-
const [value, setValue] = useSessionStorage("myKey", "default");
|
|
481
|
-
|
|
482
|
-
setValue("newValue");
|
|
483
|
-
console.log(value);
|
|
484
|
-
```
|
|
485
|
-
|
|
486
|
-
---
|
|
487
|
-
📌 **useCookie**
|
|
488
|
-
Manages cookies by providing functions to get, set, and delete a specific cookie by its key.
|
|
489
|
-
|
|
490
|
-
```ts
|
|
491
|
-
const [token, setToken, deleteToken] = useCookie('token');
|
|
492
|
-
|
|
493
|
-
setToken('abc123');
|
|
494
|
-
deleteToken();
|
|
495
|
-
```
|
|
496
|
-
---
|
|
497
|
-
📌 **usePersistedState**
|
|
498
|
-
Stores and retrieves state from `localStorage` to persist data across page reloads.
|
|
499
|
-
|
|
500
|
-
```ts
|
|
501
|
-
const [theme, setTheme] = usePersistedState('theme', 'light');
|
|
502
|
-
```
|
|
503
|
-
---
|
|
504
|
-
📌 **useHistory**
|
|
505
|
-
Provides methods to navigate the browser history, including pushing and replacing history states, as well as moving back and forward in the history stack.
|
|
506
|
-
|
|
507
|
-
```ts
|
|
508
|
-
const {
|
|
509
|
-
history,
|
|
510
|
-
state,
|
|
511
|
-
push,
|
|
512
|
-
replace,
|
|
513
|
-
goBack,
|
|
514
|
-
goForward
|
|
515
|
-
} = useHistory();
|
|
516
|
-
|
|
517
|
-
push('/about', { from: 'home' });
|
|
518
|
-
replace('/profile');
|
|
519
|
-
goBack();
|
|
520
|
-
goForward();
|
|
521
|
-
```
|
|
522
|
-
|
|
523
|
-
---
|
|
524
|
-
📌 **useRecentSearch**
|
|
525
|
-
Return and manage recent searched history.
|
|
526
|
-
|
|
527
|
-
```ts
|
|
528
|
-
const { recentSearches, addSearch, clearSearch, hasSearch } = useRecentSearch<SearchItem>({
|
|
529
|
-
key: 'myRecentItems',
|
|
530
|
-
limit: 5,
|
|
531
|
-
uniqueKey: 'id',
|
|
532
|
-
excludeEmpty: true,
|
|
533
|
-
});
|
|
534
|
-
|
|
535
|
-
```
|
|
536
|
-
---
|
|
537
|
-
📌 **useHistoryState**
|
|
538
|
-
Manages state history with undo/redo capabilities.
|
|
539
|
-
|
|
540
|
-
```ts
|
|
541
|
-
const { state, setState, undo, redo } = useHistoryState(initialState);
|
|
542
|
-
|
|
543
|
-
// Example
|
|
544
|
-
setState({...});
|
|
545
|
-
undo(); // Reverts change
|
|
546
|
-
```
|
|
547
|
-
---
|
|
548
|
-
📌 **useVisibilityChange**
|
|
549
|
-
Tracks the visibility state of the document and returns whether the page is currently visible or hidden.
|
|
550
|
-
|
|
551
|
-
```ts
|
|
552
|
-
const isVisible = useVisibilityChange(); // ➝ true | false
|
|
553
|
-
```
|
|
554
|
-
---
|
|
555
|
-
📌 **useDarkMode**
|
|
556
|
-
Detects and manages dark mode preferences in the browser.
|
|
557
|
-
|
|
558
|
-
```ts
|
|
559
|
-
const [isDarkMode, toggleDarkMode] = useDarkMode();
|
|
560
|
-
```
|
|
561
|
-
---
|
|
562
|
-
📌 **usePreferredLanguage**
|
|
563
|
-
Detects the preferred language set in the browser.
|
|
564
|
-
|
|
565
|
-
```ts
|
|
566
|
-
const language = usePreferredLanguage();
|
|
567
|
-
```
|
|
568
|
-
---
|
|
569
|
-
📌 **useIndexedDB**
|
|
570
|
-
Provides a hook to interact with IndexedDB in the browser, enabling persistent client-side storage.
|
|
571
|
-
|
|
572
|
-
```ts
|
|
573
|
-
const { data, setData } = useIndexedDB('dbName');
|
|
574
|
-
```
|
|
575
|
-
---
|
|
576
|
-
|
|
577
|
-
📌 **useMediaQuery**
|
|
578
|
-
Checks if a media query condition matches the current viewport, useful for responsive design.
|
|
579
|
-
|
|
580
|
-
```ts
|
|
581
|
-
const isMobile = useMediaQuery('(max-width: 768px)');
|
|
582
|
-
```
|
|
583
|
-
---
|
|
584
|
-
📌 **useWindowSize**
|
|
585
|
-
Returns the current window size (width and height).
|
|
586
|
-
|
|
587
|
-
```ts
|
|
588
|
-
const { width, height } = useWindowSize();
|
|
589
|
-
```
|
|
590
|
-
---
|
|
591
|
-
📌 **useResizeObserver**
|
|
592
|
-
Observes and returns the dimensions of an HTML element using the `ResizeObserver` API.
|
|
593
|
-
|
|
594
|
-
```ts
|
|
595
|
-
const size = useResizeObserver(ref);
|
|
596
|
-
|
|
597
|
-
// size = { width: 200, height: 100 }
|
|
598
|
-
```
|
|
599
|
-
---
|
|
600
|
-
📌 **useScrollPosition**
|
|
601
|
-
Tracks the horizontal (x) and vertical (y) scroll positions of the window.
|
|
602
|
-
|
|
603
|
-
```ts
|
|
604
|
-
const { x, y } = useScrollPosition();
|
|
605
|
-
```
|
|
606
|
-
---
|
|
607
|
-
📌 **useScrollDirection**
|
|
608
|
-
Determines whether the user is scrolling up or down based on window scroll position changes.
|
|
609
|
-
|
|
610
|
-
```ts
|
|
611
|
-
const direction = useScrollDirection(); // ➝ 'up' | 'down'
|
|
612
|
-
```
|
|
613
|
-
|
|
614
|
-
📌 **useScrollLock**
|
|
615
|
-
Locks or unlocks scrolling on the page.
|
|
616
|
-
|
|
617
|
-
```ts
|
|
618
|
-
useScrollLock(true); // Lock scrolling
|
|
619
|
-
useScrollLock(false); // Unlock scrolling
|
|
620
|
-
```
|
|
621
|
-
---
|
|
622
|
-
📌 **useLockBodyScroll**
|
|
623
|
-
Prevents scrolling on the body element, useful for modals or off-canvas menus.
|
|
624
|
-
|
|
625
|
-
```ts
|
|
626
|
-
useLockBodyScroll(true);
|
|
627
|
-
```
|
|
628
|
-
---
|
|
629
|
-
📌 **useCss**
|
|
630
|
-
Allows injecting dynamic CSS rules into the document.
|
|
631
|
-
|
|
632
|
-
```ts
|
|
633
|
-
useCss('.class { color: red; }');
|
|
634
|
-
```
|
|
635
|
-
---
|
|
636
|
-
📌 **useReducedMotion**
|
|
637
|
-
Detects whether the user has reduced motion settings in their OS preferences.
|
|
638
|
-
|
|
639
|
-
```ts
|
|
640
|
-
const prefersReducedMotion = useReducedMotion();
|
|
641
|
-
```
|
|
642
|
-
---
|
|
643
|
-
📌 **useImageLoader**
|
|
644
|
-
Provides a way to load and display images in a way that improves performance and loading behavior.
|
|
645
|
-
|
|
646
|
-
```ts
|
|
647
|
-
const { isLoading, image } = useImageLoader('imageURL');
|
|
648
|
-
```
|
|
649
|
-
|
|
650
|
-
---
|
|
651
|
-
|
|
652
|
-
📌 **useBattery**
|
|
653
|
-
Monitors the battery status of the device, including level, charging status, and remaining charging or discharging time.
|
|
654
|
-
|
|
655
|
-
```ts
|
|
656
|
-
const { level, charging, supported, loading, chargingTime, dischargingTime } = useBattery();
|
|
657
|
-
```
|
|
658
|
-
---
|
|
659
|
-
📌 **useGeoLocation**
|
|
660
|
-
Retrieves the user's current geographic location and returns it along with any error encountered.
|
|
661
|
-
|
|
662
|
-
```ts
|
|
663
|
-
const { position, error } = useGeoLocation();
|
|
664
|
-
```
|
|
665
|
-
---
|
|
666
|
-
📌 **useMousePosition**
|
|
667
|
-
Tracks the user's mouse position in real-time and returns the coordinates.
|
|
668
|
-
|
|
669
|
-
```ts
|
|
670
|
-
const { x, y } = useMousePosition();
|
|
671
|
-
```
|
|
672
|
-
|
|
673
|
-
---
|
|
674
|
-
📌 **useOnlineStatus**
|
|
675
|
-
Monitors the user's network connection status (online/offline).
|
|
676
|
-
|
|
677
|
-
```ts
|
|
678
|
-
const isOnline = useOnlineStatus();
|
|
679
|
-
```
|
|
680
|
-
|
|
681
|
-
---
|
|
682
|
-
|
|
683
|
-
📌 **useSound**
|
|
684
|
-
Controls the playback of an audio file, including play, pause, and stop functionalities, while also managing the audio volume and handling any errors.
|
|
685
|
-
|
|
686
|
-
```ts
|
|
687
|
-
const {
|
|
688
|
-
play,
|
|
689
|
-
pause,
|
|
690
|
-
stop,
|
|
691
|
-
setVolume,
|
|
692
|
-
isPlaying,
|
|
693
|
-
error
|
|
694
|
-
} = useSound("/sound.mp3");
|
|
695
|
-
|
|
696
|
-
play();
|
|
697
|
-
pause();
|
|
698
|
-
stop();
|
|
699
|
-
setVolume(0.5);
|
|
700
|
-
```
|
|
701
|
-
---
|
|
702
|
-
📌 **useSpeak**
|
|
703
|
-
Converts text to speech using the Web Speech API, allowing the text to be spoken and handling errors.
|
|
704
|
-
```ts
|
|
705
|
-
const { speak, error } = useSpeak('Hello world!');
|
|
706
|
-
speak();
|
|
707
|
-
```
|
|
708
|
-
---
|
|
709
|
-
|
|
710
|
-
### 📌 **usePermission**
|
|
711
|
-
Monitors the status of a specific browser permission (like geolocation, camera, microphone, etc.) and updates reactively when the permission state changes.
|
|
712
|
-
|
|
713
|
-
```ts
|
|
714
|
-
const permission = usePermission({ name: 'geolocation' });
|
|
715
|
-
```
|
|
716
|
-
|
|
717
|
-
---
|
|
718
|
-
|
|
719
|
-
### 📌 **usePageLeave**
|
|
720
|
-
Detects when the mouse leaves the viewport (commonly used to detect exit intent on websites).
|
|
721
|
-
|
|
722
|
-
```ts
|
|
723
|
-
usePageLeave(() => {
|
|
724
|
-
console.log('Mouse left the page');
|
|
725
|
-
});
|
|
726
|
-
```
|
|
727
|
-
|
|
728
|
-
---
|
|
729
|
-
|
|
730
|
-
### 📌 **useMotion**
|
|
731
|
-
Subscribes to device motion events (like `acceleration` or `rotation`) and returns the latest motion values from sensors on mobile devices.
|
|
732
|
-
|
|
733
|
-
```ts
|
|
734
|
-
const motion = useMotion();
|
|
735
|
-
console.log(motion.acceleration);
|
|
736
|
-
```
|
|
737
|
-
|
|
738
|
-
---
|
|
739
|
-
|
|
740
|
-
### 📌 **useHoverDirty**
|
|
741
|
-
Returns `true` when the mouse is hovering over a target element. Unlike `useHover`, this doesn't handle delays or complex state logic—just raw hover state.
|
|
742
|
-
|
|
743
|
-
```ts
|
|
744
|
-
const ref = useRef(null);
|
|
745
|
-
const isHovered = useHoverDirty(ref);
|
|
746
|
-
```
|
|
747
|
-
|
|
748
|
-
---
|
|
749
|
-
|
|
750
|
-
### 📌 **useBeforeUnload**
|
|
751
|
-
Prompts the user with a confirmation dialog before leaving the page (refresh, close tab, etc.).
|
|
752
|
-
|
|
753
|
-
```ts
|
|
754
|
-
useBeforeUnload(true); // Triggers default browser dialog
|
|
755
|
-
```
|
|
756
|
-
|
|
757
|
-
---
|
|
758
|
-
|
|
759
|
-
### 📌 **useClickAway**
|
|
760
|
-
Triggers a handler function when a user clicks outside of a specified element.
|
|
761
|
-
|
|
762
|
-
```ts
|
|
763
|
-
const ref = useRef(null);
|
|
764
|
-
useClickAway(ref, () => {
|
|
765
|
-
console.log('Clicked outside');
|
|
766
|
-
});
|
|
767
|
-
```
|
|
768
|
-
|
|
769
|
-
---
|
|
770
|
-
|
|
771
|
-
### 📌 **useResponsive**
|
|
772
|
-
Tracks screen size and returns breakpoint-based flags (`xs`, `sm`, `md`, etc.) to help in building responsive UI layouts.
|
|
773
|
-
|
|
774
|
-
```ts
|
|
775
|
-
const screens = useResponsive();
|
|
776
|
-
console.log(screens.md); // true or false
|
|
777
|
-
```
|
|
778
|
-
|
|
779
|
-
---
|
|
780
|
-
|
|
781
|
-
### 📌 **useUnmountedRef**
|
|
782
|
-
Returns a `ref` that indicates whether the component is currently unmounted—useful to prevent state updates on unmounted components.
|
|
783
|
-
|
|
784
|
-
```ts
|
|
785
|
-
const unmountedRef = useUnmountedRef();
|
|
786
|
-
```
|
|
787
|
-
---
|
|
788
|
-
📌 **useCountUp**
|
|
789
|
-
Animates a counter that counts up from 0 to a target value within a specified duration, returning the current count and any errors.
|
|
790
|
-
|
|
791
|
-
```ts
|
|
792
|
-
const { count, error } = useCountUp(100, 5000); // counts up to 100 in 5s
|
|
793
|
-
```
|
|
794
|
-
|
|
795
|
-
---
|
|
796
|
-
📌 **useCountDown**
|
|
797
|
-
Counts down from a specified start value to zero, updating every second and returning the current count and any errors.
|
|
798
|
-
|
|
799
|
-
```ts
|
|
800
|
-
const { count, error } = useCountDown(10); // counts down from 10
|
|
801
|
-
```
|
|
802
|
-
|
|
803
|
-
---
|
|
804
|
-
|
|
805
|
-
📌 **useWebSocket**
|
|
806
|
-
Manages WebSocket connections with auto-reconnect.
|
|
807
|
-
|
|
808
|
-
```ts
|
|
809
|
-
const { send, message, status } = useWebSocket('ws://api.example.com');
|
|
810
|
-
|
|
811
|
-
// Example
|
|
812
|
-
send(JSON.stringify({ action: 'ping' }));
|
|
813
|
-
```
|
|
814
|
-
|
|
815
|
-
---
|
|
816
33
|
|
|
817
34
|
**License**
|
|
818
35
|
|
|
@@ -34,7 +34,7 @@ interface ISpeakResult {
|
|
|
34
34
|
isSupported: boolean;
|
|
35
35
|
error: Error | null;
|
|
36
36
|
}
|
|
37
|
-
export declare
|
|
37
|
+
export declare const useSpeak: () => ISpeakResult;
|
|
38
38
|
export declare function useCountUp(target: number, duration: number): {
|
|
39
39
|
count: number;
|
|
40
40
|
error: Error | null;
|
|
@@ -61,7 +61,7 @@ export function useCss(css) {
|
|
|
61
61
|
return { error };
|
|
62
62
|
}
|
|
63
63
|
const IS_SUPPORTED = typeof window !== 'undefined' && 'speechSynthesis' in window;
|
|
64
|
-
export
|
|
64
|
+
export const useSpeak = () => {
|
|
65
65
|
const [status, setStatus] = useState('idle');
|
|
66
66
|
const [error, setError] = useState(null);
|
|
67
67
|
const isMounted = useRef(true);
|
|
@@ -135,7 +135,8 @@ export function useSpeak() {
|
|
|
135
135
|
};
|
|
136
136
|
// Cancel any ongoing speech
|
|
137
137
|
window.speechSynthesis.cancel();
|
|
138
|
-
|
|
138
|
+
if (isMounted.current)
|
|
139
|
+
setError(null);
|
|
139
140
|
// Build utterance
|
|
140
141
|
const utterance = new SpeechSynthesisUtterance(trimmed);
|
|
141
142
|
utterance.rate = (_c = options.rate) !== null && _c !== void 0 ? _c : 1;
|
|
@@ -176,8 +177,13 @@ export function useSpeak() {
|
|
|
176
177
|
(_b = (_a = callbacksRef.current).onError) === null || _b === void 0 ? void 0 : _b.call(_a, err);
|
|
177
178
|
utteranceRef.current = null;
|
|
178
179
|
};
|
|
180
|
+
// Assign ref BEFORE timeout — prevents Chrome GC dropping utterance mid-speech
|
|
179
181
|
utteranceRef.current = utterance;
|
|
180
|
-
|
|
182
|
+
// Chrome gets stuck in paused state after cancel() — delay lets it settle
|
|
183
|
+
setTimeout(() => {
|
|
184
|
+
if (isMounted.current)
|
|
185
|
+
window.speechSynthesis.speak(utterance);
|
|
186
|
+
}, 100);
|
|
181
187
|
}, [safeSetStatus, safeSetError]); // minimal deps — text passed at call time
|
|
182
188
|
return {
|
|
183
189
|
speak,
|
|
@@ -190,7 +196,7 @@ export function useSpeak() {
|
|
|
190
196
|
isSupported: IS_SUPPORTED,
|
|
191
197
|
error,
|
|
192
198
|
};
|
|
193
|
-
}
|
|
199
|
+
};
|
|
194
200
|
export function useCountUp(target, duration) {
|
|
195
201
|
const [count, setCount] = useState(0);
|
|
196
202
|
const [error, setError] = useState(null);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-hook-toolkit",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Ultimate package for React developers, offering a powerful collection of hooks and components to enhance their development experience.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|