react-hook-toolkit 3.0.5 → 5.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 CHANGED
@@ -1,819 +1,289 @@
1
-
2
- **react-hook-toolkit** package offers a comprehensive set of hooks to simplify React development. It includes hooks for managing state, handling API requests, optimizing performance, and improving user interactions. Key features include data fetching, form handling, local storage management, debouncing/throttling, window size tracking, event listeners, and more. These hooks are designed to enhance productivity by providing reusable, easy-to-use solutions for common tasks.
3
-
4
- **Note : This lightweight and type-safe package is written in TypeScript and offers full support for all hooks across all modern browsers.**
5
-
6
- ### Installation
7
-
8
- Install the package:
9
-
10
- ```bash
11
- npm install react-hook-toolkit
12
- # or
13
- pnpm add react-hook-toolkit
14
- ```
15
-
16
- ### **Authors**
17
-
18
- ![NPM](https://img.shields.io/badge/Author-React_Developers-red)   ![npm](https://img.shields.io/npm/v/react-hook-toolkit?color=1C939D)   ![npm](https://img.shields.io/npm/dt/react-hook-toolkit)   ![NPM](https://img.shields.io/npm/l/react-hook-toolkit)   ![NPM Unpacked Size](https://img.shields.io/npm/unpacked-size/react-hook-toolkit)
19
-
20
- ### **Browser Support**
21
-
22
- | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png)
23
- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
24
- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
25
-
26
-
27
- ### **Features**
28
- Here's the properly structured documentation with clear purpose explanations:
29
-
30
- ------------------------------------------ **Custom Hooks** ------------------------------------------------
31
-
32
- 📌 **useBrowser**
33
- Provides comprehensive browser control and environment detection with a unified API for navigation, window management, and system interactions.
34
-
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
-
817
- **License**
818
-
819
- [MIT](https://docs.npmjs.com/policies/npm-license) © (2022-2024)
1
+
2
+ **react-hook-toolkit** package offers a comprehensive set of hooks to simplify React development. It includes hooks for managing state, handling API requests, optimizing performance, and improving user interactions. Key features include data fetching, form handling, local storage management, debouncing/throttling, window size tracking, event listeners, and more. These hooks are designed to enhance productivity by providing reusable, easy-to-use solutions for common tasks.
3
+
4
+ **Note : This lightweight and type-safe package is written in TypeScript and offers full support for all hooks across all modern browsers.**
5
+
6
+ ### Installation
7
+
8
+ Install the package:
9
+
10
+ ```bash
11
+ npm install react-hook-toolkit
12
+ # or
13
+ pnpm add react-hook-toolkit
14
+ ```
15
+
16
+ ### **Authors**
17
+
18
+ ![NPM](https://img.shields.io/badge/Author-React_Developers-red) &nbsp; ![npm](https://img.shields.io/npm/v/react-hook-toolkit?color=1C939D) &nbsp; ![npm](https://img.shields.io/npm/dt/react-hook-toolkit) &nbsp; ![NPM](https://img.shields.io/npm/l/react-hook-toolkit) &nbsp; ![NPM Unpacked Size](https://img.shields.io/npm/unpacked-size/react-hook-toolkit)
19
+
20
+ ### **Browser Support**
21
+
22
+ | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png)
23
+ | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
24
+ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
25
+
26
+
27
+ ### **Documentation**
28
+
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.
30
+
31
+ 👉 https://react-hook-toolkit.netlify.app
32
+
33
+
34
+ ---
35
+
36
+ ## Available Hooks
37
+
38
+ ### 🔄 State & Data Management
39
+
40
+ | Hook | Description |
41
+ |------|-------------|
42
+ | `useToggle` | Boolean toggle with a stable flip function |
43
+ | `useBoolean` | Boolean with explicit `setTrue` / `setFalse` / `toggle` / `set` |
44
+ | `usePrevious` | Returns the value from the previous render |
45
+ | `useArray` | Array state with push, removeByIndex, clear helpers |
46
+ | `useList` | Array state with rich set/push/removeAt/insertAt/updateAt/clear actions |
47
+ | `useCounter` | Numeric counter with min/max/step bounds and increment/decrement/reset/set |
48
+ | `useMap` | Map data structure as React state with get/set/delete/clear |
49
+ | `useSet` | Set data structure as React state with add/delete/toggle/clear |
50
+ | `useQueue` | FIFO queue with enqueue/dequeue/peek/clear |
51
+ | `useStack` | LIFO stack with push/pop/peek/clear |
52
+ | `useUndo` | Simple undo/redo state stack |
53
+ | `useHistoryState` | Full undo/redo history with past, present, and future arrays |
54
+ | `useHistory` | push/replace/goBack/goForward wrappers around the History API |
55
+ | `useStateWithCallback` | setState that fires a callback after the update is applied |
56
+ | `useMergeState` | Object state with partial merge (like class component setState) |
57
+ | `useResetState` | useState augmented with a reset() that restores the initial value |
58
+ | `useSyncedState` | State synced across browser tabs/windows via BroadcastChannel |
59
+ | `useDerivedState` | Memoized value computed from a source with explicit transform |
60
+ | `usePatch` | Object state with a patch() method for one-level deep partial updates |
61
+ | `usePersistedState` | useState synced to localStorage |
62
+ | `useSafeState` | Suppresses state updates after component unmount |
63
+ | `useRafState` | Batches state updates via requestAnimationFrame |
64
+ | `useForceUpdate` | Returns a function that forces a component re-render |
65
+ | `useGenericReducer` | Factory for creating typed reducers |
66
+
67
+ ### 🌐 Fetching & API
68
+
69
+ | Hook | Description |
70
+ |------|-------------|
71
+ | `useAsync` | Runs an async function on mount, tracks status/value/error |
72
+ | `useAsyncCallback` | Imperative async wrapper isPending/data/error/reset; does not auto-run |
73
+ | `useRequest` | Fetches JSON from a URL, returns `{ data, loading, error }` |
74
+ | `useRequestRetry` | Like `useRequest` with automatic retry on failure |
75
+ | `useAbortFetch` | Fetch with AbortController — auto-cancels on unmount or URL change |
76
+ | `useLazyFetch` | Fetch triggered manually (not on mount) |
77
+ | `usePolling` | Repeatedly calls an async fetcher on a fixed interval |
78
+ | `useOptimisticUpdate` | Applies an optimistic value immediately, rolls back on error |
79
+ | `useInfiniteScroll` | Loads paginated data as the user scrolls to the bottom |
80
+ | `useWebSocket` | Connects to a WebSocket and exposes data/send/isConnected |
81
+
82
+ ### ⏱ Timing & Async
83
+
84
+ | Hook | Description |
85
+ |------|-------------|
86
+ | `useDebounce` | Debounced copy of a value |
87
+ | `useDebouncedValue` | Alias for `useDebounce` |
88
+ | `useDebouncedCallback` | Debounced callback function |
89
+ | `useDebouncedState` | State that only updates after the setter hasn't been called for N ms |
90
+ | `useThrottle` | Throttled copy of a value |
91
+ | `useDelay` | Delays propagation of a value by a fixed time |
92
+ | `useInterval` | Runs a callback on a repeating interval |
93
+ | `useTimeout` | Runs a callback once after a delay |
94
+ | `useTimer` | Countdown timer that decrements every second |
95
+ | `useCountUp` | Animates a number from 0 up to a target |
96
+ | `useCountDown` | Animates a number from a start value down to 0 |
97
+ | `useClock` | Returns a live `Date` updated every N milliseconds |
98
+ | `useStopwatch` | Start/stop/reset/lap elapsed-time stopwatch in milliseconds |
99
+ | `useAnimationFrame` | Calls a callback on every rAF frame; returns start/stop/isRunning |
100
+ | `useIdleCallback` | Schedules a callback with requestIdleCallback (setTimeout fallback) |
101
+ | `useAsyncEffect` | useEffect wrapper that accepts an async function with cancellation guard |
102
+
103
+ ### 💾 Browser Storage
104
+
105
+ | Hook | Description |
106
+ |------|-------------|
107
+ | `useLocalStorage` | Reads/writes a localStorage key as state |
108
+ | `useSessionStorage` | Reads/writes a sessionStorage key as state |
109
+ | `useCookie` | Reads, writes, and deletes a browser cookie |
110
+ | `useIndexedDB` | Reads all records from an IndexedDB object store |
111
+ | `usePersistedForm` | Form state that auto-saves to localStorage |
112
+ | `usePersistedState` | Generic state synced to localStorage |
113
+
114
+ ### 📐 DOM & Layout
115
+
116
+ | Hook | Description |
117
+ |------|-------------|
118
+ | `useWindowSize` | Reactive window width and height |
119
+ | `useResizeObserver` | Observes size changes on a ref'd element |
120
+ | `useMeasure` | Full bounding rect of a ref'd element, updates on resize |
121
+ | `useRect` | Reactive bounding DOMRect via ResizeObserver + scroll — returns `[ref, rect]` |
122
+ | `useScrollPosition` | Current page scroll X/Y |
123
+ | `useScrollDirection` | Whether the user is scrolling `'up'` or `'down'` |
124
+ | `useScrollLock` | Locks/unlocks `document.body` overflow |
125
+ | `useLockBodyScroll` | Locks body scroll and compensates for scrollbar width |
126
+ | `useScrollToTop` | Returns `[isVisible, scrollToTop]` shows button after threshold |
127
+ | `useScrollIntoView` | Returns ref + function that scrolls the element into the viewport |
128
+ | `useScrollThreshold` | Returns true when page (or element) has scrolled past a pixel offset |
129
+ | `useMousePosition` | Current mouse X/Y relative to the viewport |
130
+ | `useIntersectionObserver` | Tracks whether a ref'd element is visible in the viewport |
131
+ | `useInView` | Convenience `[ref, inView]` wrapper over IntersectionObserver; supports `once` |
132
+ | `useMutationObserver` | Observes DOM mutations on a ref'd element |
133
+ | `useGridLayout` | Tracks CSS grid column and row count of a ref'd element |
134
+ | `useVirtualList` | Windowed (virtual) list — only renders visible items |
135
+ | `useFocusTrap` | Traps keyboard Tab focus within a container (for modals/dialogs) |
136
+ | `useEventListener` | Attaches a single event listener to an element or window |
137
+ | `useEventListeners` | Attaches an event listener with a stable handler ref |
138
+ | `useScript` | Dynamically loads an external script and reports its status |
139
+ | `useCss` | Injects a CSS string into the document head |
140
+ | `useImageLoader` | Tracks loaded/error state of an image src |
141
+ | `useTitle` | Reactively sets `document.title`; optionally restores it on unmount |
142
+ | `useFavicon` | Dynamically updates the page favicon href |
143
+
144
+ ### 🎨 UI & Interaction
145
+
146
+ | Hook | Description |
147
+ |------|-------------|
148
+ | `useDarkMode` | Tracks and toggles dark mode preference |
149
+ | `useTheme` | light/dark/system theme with localStorage persistence and `data-theme` attribute |
150
+ | `useBreakpoint` | Named breakpoint (`xs`/`sm`/`md`/`lg`/`xl`/`2xl`) from window width |
151
+ | `useMediaQuery` | Returns true when a CSS media query matches |
152
+ | `useReducedMotion` | Returns true when the user prefers reduced motion |
153
+ | `useRipple` | Material-style ripple effect — returns ripple entries and onMouseDown handler |
154
+ | `useToast` | Toast notification state manager with auto-dismiss |
155
+ | `useModal` | Modal open/close state with body scroll lock |
156
+ | `useContextMenu` | Right-click context menu position state |
157
+ | `useHover` | Tracks hover via mouseenter/mouseleave, returns `[ref, isHovered]` |
158
+ | `useHoverDirty` | Tracks hover via mouseover/mouseout on a ref'd element |
159
+ | `useFocus` | Tracks focus state of a ref'd element with programmatic focus/blur |
160
+ | `useClickAway` | Calls a handler when a click occurs outside a ref'd element |
161
+ | `useLongPress` | Fires a callback after a sustained press (mouse or touch) |
162
+ | `useTouch` | Tracks touchstart/touchmove/touchend coordinates on an element |
163
+ | `useSwiping` | Detects swipe gestures (left/right/up/down) with directional callbacks |
164
+ | `usePointers` | Handles all pointer events and tracks active pointers by pointerId |
165
+ | `useDragAndDrop` | Container + draggable item props with `onDrop(from, to)` callback |
166
+ | `useDragReorder` | Drag-and-drop list reordering |
167
+ | `useFileDropArea` | File drag-drop + input handling with type/size validation |
168
+ | `useSelection` | Returns currently selected text and its bounding DOMRect |
169
+
170
+ ### ⌨️ Input & Forms
171
+
172
+ | Hook | Description |
173
+ |------|-------------|
174
+ | `useInput` | Controlled input state with value/onChange/reset and spread-ready `bind` |
175
+ | `useCheckbox` | Controlled checkbox state with toggle and spread-ready `bind` |
176
+ | `useForm` | Basic form values + per-field validation |
177
+ | `useSmartForm` | Form with auto-save to localStorage and dirty tracking |
178
+ | `useFormSubmit` | Wraps an async submit handler with isSubmitting/submitError |
179
+ | `useFormWizard` | Multi-step form wizard with per-step validation |
180
+ | `useFieldArray` | Dynamic field arrays with append/remove/update |
181
+ | `useCrossFieldValidation` | Cross-field validation returning per-field errors |
182
+ | `useValidation` | Standalone field validation with an array of validator functions |
183
+ | `useSearch` | Search query state with filtered results and optional debounce |
184
+ | `useFilter` | Filters an array by a predicate function |
185
+ | `useSort` | Sorts an array by key with direction toggling |
186
+ | `useAutocomplete` | Suggestions list with keyboard navigation (Up/Down/Enter/Escape) |
187
+
188
+ ### 🧭 Navigation & Routing
189
+
190
+ | Hook | Description |
191
+ |------|-------------|
192
+ | `useRouter` | Minimal client-side router with pathname, searchParams, and navigate |
193
+ | `useNavigationState` | Tracks pathname/search/state from pushState/popstate |
194
+ | `useHistoryState` | Undo/redo state with full history (past/present/future) |
195
+ | `useMenuNavigation` | Flattens nested menu data and handles path-based selection |
196
+ | `useHash` | Reads and writes the URL hash fragment as state |
197
+ | `useQueryParams` | Reads and writes URL search parameters reactively |
198
+ | `useParams` | Extracts named dynamic route parameters from the current URL path |
199
+ | `usePagination` | Client-side pagination: page, pageSize, totalPages, offset, next/prev/goTo |
200
+
201
+ ### 🔐 Auth & Permissions
202
+
203
+ | Hook | Description |
204
+ |------|-------------|
205
+ | `usePermission` | Queries the Permissions API for a descriptor |
206
+
207
+ ### 📡 Browser & Device
208
+
209
+ | Hook | Description |
210
+ |------|-------------|
211
+ | `useBattery` | Battery level, charging state, and charge/discharge times |
212
+ | `useGeoLocation` | Current geolocation position |
213
+ | `useOnlineStatus` | Whether the browser is online |
214
+ | `useNetwork` | Network info: effectiveType, downlink, rtt, saveData |
215
+ | `useNetworkState` | Full NetworkInformation API with `since` timestamp |
216
+ | `useOrientation` | Device screen orientation type/angle with isPortrait/isLandscape |
217
+ | `usePreferredLanguage` | Navigator language and languages list |
218
+ | `useIdle` | Detects user inactivity after a configurable timeout |
219
+ | `usePageVisibility` | Returns true when the current browser tab is visible |
220
+ | `useBrowser` | Full browser controls: navigate, reload, fullscreen, clipboard, share, and more |
221
+ | `useFullscreen` | Fullscreen API for a ref'd element with enter/exit/toggle |
222
+ | `useMediaDevices` | getUserMedia access + device enumeration for camera and microphone |
223
+ | `useAudioAnalyser` | Real-time audio frequency and time-domain data via AnalyserNode |
224
+ | `useScreenCapture` | Screen/window/tab capture via getDisplayMedia |
225
+ | `useGamepad` | Polls Gamepad API state on every rAF frame |
226
+ | `useNotification` | Web Notifications API — request permission and show notifications |
227
+ | `useVibration` | Vibration API — trigger device vibration with a pattern |
228
+ | `useWakeLock` | Screen Wake Lock API — prevents screen from sleeping |
229
+ | `useShareSheet` | Web Share API — triggers the native OS share sheet |
230
+ | `useMotion` | Device motion sensor (acceleration, rotation rate) |
231
+ | `useWorker` | Runs a function in a Web Worker background thread |
232
+
233
+ ### 🗣 Speech & Audio
234
+
235
+ | Hook | Description |
236
+ |------|-------------|
237
+ | `useSpeech` | Text-to-speech via the SpeechSynthesis API (declarative) |
238
+ | `useSpeak` | Text-to-speech with imperative speak/stop/pause/resume controls |
239
+ | `useVoice` | Speech recognition with command matching, history, wake word, and shortcuts |
240
+ | `useSound` | HTML audio player with play/pause/stop/setVolume controls |
241
+
242
+ ### 🔁 Lifecycle & Utilities
243
+
244
+ | Hook | Description |
245
+ |------|-------------|
246
+ | `useIsMounted` | Returns true after the component mounts |
247
+ | `useIsFirstRender` | Returns true only on the very first render |
248
+ | `useUnmountedRef` | Ref that becomes true after the component unmounts |
249
+ | `useUpdateEffect` | Like useEffect but skips the first (mount) run |
250
+ | `useIsomorphicEffect` | useLayoutEffect on the browser, useEffect on the server (SSR-safe) |
251
+ | `useBeforeUnload` | Prompts the user before leaving the page |
252
+ | `usePageLeave` | Fires a callback when the mouse leaves the page |
253
+ | `useVisibilityChange` | Returns true when the browser tab is visible |
254
+ | `useLatest` | Ref that always holds the most recent value — avoids stale closures |
255
+ | `useEventCallback` | Stable callback ref — safe for event listeners without re-subscribing |
256
+ | `useStableCallback` | Semantic alias for useEventCallback |
257
+ | `useConstant` | Evaluates an initializer once and never recomputes it |
258
+ | `useComputed` | Memoized derived value — semantic alias for useMemo |
259
+ | `useDeepCompareEffect` | useEffect with deep equality dep comparison |
260
+ | `useDeepCompareMemo` | useMemo with deep equality dep comparison |
261
+ | `useShallowEqual` | Returns the previous (stable) reference when value is shallowly equal |
262
+ | `useStepper` | Step wizard with next/back/reset/goto and isFirstStep/isLastStep |
263
+ | `useRecentSearch` | Persists and manages a recent-searches list in localStorage |
264
+ | `useEventEmitter` | In-component pub/sub: on/off/emit/once/clear |
265
+ | `useClipboard` | Copy text to the clipboard with a copied state |
266
+ | `useScrollIntoView` | Returns ref + scrollIntoView() function |
267
+
268
+ ### 🛠 Context & Optimization
269
+
270
+ | Hook | Description |
271
+ |------|-------------|
272
+ | `createOptimizedContext` | Creates a context with a selector-based hook to avoid unnecessary re-renders |
273
+ | `useDrawer` | Consumes the DrawerContext (open/close/state) |
274
+
275
+ ### 🐛 Developer Tools
276
+
277
+ | Hook | Description |
278
+ |------|-------------|
279
+ | `useWhyDidYouUpdate` | Logs which props/state changed to trigger the last render (dev only) |
280
+ | `useLogger` | Logs a label and values on every render (dev only) |
281
+ | `useRenderCount` | Returns the number of times the component has rendered |
282
+ | `useErrorBoundary` | Imperative showBoundary(error) to surface errors to the nearest ErrorBoundary |
283
+ | `useReducerLogger` | Wraps useReducer to log every action and state change (dev only) |
284
+
285
+ ---
286
+
287
+ **License**
288
+
289
+ [MIT](https://docs.npmjs.com/policies/npm-license) © (2022-2024)