react-hook-toolkit 0.0.3 → 0.0.5

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 ADDED
@@ -0,0 +1,121 @@
1
+ **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.
2
+
3
+ ## Installation
4
+
5
+ Install the package with npm:
6
+
7
+ ```bash
8
+ npm i react-hook-toolkit
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **`useAxios`**: A custom hook for making API requests using Axios. It manages request states (`loading`, `error`, `data`) and provides a function (`makeRequest`) to initiate a request.
14
+
15
+ - **`useAdvReducer`**: A custom reducer function that takes an `initialState` and an object of actions, returning a new state based on the action type.
16
+
17
+ - **`useFetch`**: Fetches data from a given URL and manages the loading, error, and data states.
18
+
19
+ - **`useLocalStorage`**: A hook to persist state in `localStorage`. It initializes state from `localStorage` and updates it whenever the value changes.
20
+
21
+ - **`useToggle`**: A simple boolean toggle hook that returns a state and a function to toggle its value.
22
+
23
+ - **`useDebounce`**: Delays updating the state until after a specified delay, useful for preventing frequent updates (e.g., handling user input).
24
+
25
+ - **`useThrottle`**: Limits how often a value updates within a given time interval, useful for performance optimization.
26
+
27
+ - **`usePrevious`**: Keeps track of the previous value of a state or prop.
28
+
29
+ - **`useMediaQuery`**: Checks if a media query matches the current viewport size and updates the state accordingly.
30
+
31
+ - **`useClipboard`**: Copies text to the clipboard and provides a state to indicate if copying was successful.
32
+
33
+ - **`useInterval`**: Runs a callback function at a specified time interval and clears it when the delay is null or the component unmounts.
34
+
35
+ - **`useWindowSize`**: Tracks the width and height of the browser window and updates when resized.
36
+
37
+ - **`useKeyPress`**: Detects whether a specific key is being pressed or released.
38
+
39
+ - **`useOnlineStatus`**: Monitors the user's network connection status (online/offline).
40
+
41
+ - **`useScrollPosition`**: Tracks the horizontal (x) and vertical (y) scroll positions of the window.
42
+
43
+ - **`useTimeout`**: Executes a function after a specified delay and cleans up automatically when dependencies change.
44
+
45
+ - **`useDarkMode`**: Detects and toggles dark mode based on the user's system preference.
46
+
47
+ - **`useForm`**: Manages form state, handles input changes, and performs validation using provided validators.
48
+
49
+ - **`useArray<T>`**: Provides an array state with helper functions to manipulate it, including setting, adding, removing by index, and clearing elements.
50
+
51
+ - **`useStep<T>`**: Manages step-based navigation by keeping track of the current step index and providing functions to move forward, backward, and reset.
52
+
53
+ - **`useTimeoutFn`**: Executes a callback function after a specified delay and provides functions to reset or clear the timeout.
54
+
55
+ - **`useDebouncedCallback`**: Delays the execution of a callback function until after a specified delay, resetting the delay on each call to prevent frequent execution.
56
+
57
+ - **`useScrollLock`**: Locks or unlocks scrolling on the webpage when the `lock` parameter changes.
58
+
59
+ - **`useResizeObserver<T>`**: Observes and returns the dimensions of an HTML element using the `ResizeObserver` API.
60
+
61
+ - **`useMousePosition`**: Tracks the user's mouse position in real-time and returns the coordinates.
62
+
63
+ - **`useScrollDirection`**: Determines whether the user is scrolling up or down based on window scroll position changes.
64
+
65
+ - **`useImageLoader`**: Loads an image and provides `loaded` and `error` states to track its loading status.
66
+
67
+ - **`usePersistedState<T>`**: Stores and retrieves state from `localStorage` to persist data across page reloads.
68
+
69
+ - **`useReducedMotion`**: Detects if the user has enabled the "Reduce Motion" accessibility setting in their system preferences.
70
+
71
+ - **`useCookie`**: Manages cookies by providing functions to get, set, and delete a specific cookie by its key.
72
+
73
+ - **`useFetchRetry`**: Performs an HTTP request with retry logic, retrying a specified number of times upon failure before returning an error.
74
+
75
+ - **`useDelay`**: Delays the update of a value for a specified amount of time before reflecting it in the state.
76
+
77
+ - **`useVisibilityChange`**: Tracks the visibility state of the document and returns whether the page is currently visible or hidden.
78
+
79
+ - **`useDebouncedValue`**: Debounces a value to avoid immediate changes, returning the delayed value after a specified delay.
80
+
81
+ - **`useAsync`**: Handles the state of an asynchronous function, including loading, success, and error states, with the ability to trigger the execution of the async operation.
82
+
83
+ - **`useScript`**: Dynamically loads an external script, managing its loading, ready, and error states, and optionally removes the script on unmount.
84
+
85
+ - **`useReducedMotion`**: Detects if the user has enabled the "Reduce Motion" accessibility setting and returns a boolean indicating whether reduced motion is preferred.
86
+
87
+ - **`useIndexedDB`**: Fetches data from an IndexedDB store, handling errors and updating the state with the fetched data.
88
+
89
+ - **`useGeoLocation`**: Retrieves the user's current geographic location and returns it along with any error encountered.
90
+
91
+ - **`useTimer`**: Starts a countdown timer that updates the time every second, returning the current time and any errors.
92
+
93
+ - **`useIsMounted`**: Tracks whether the component is mounted or unmounted, returning a boolean value indicating the component's mount status.
94
+
95
+ - **`useCss`**: Dynamically applies custom CSS to the document and removes it when the component unmounts, handling any errors during the process.
96
+
97
+ - **`useSpeak`**: Converts text to speech using the Web Speech API, allowing the text to be spoken and handling errors.
98
+
99
+ - **`useCountUp`**: Animates a counter that counts up from 0 to a target value within a specified duration, returning the current count and any errors.
100
+
101
+ - **`useCountDown`**: Counts down from a specified start value to zero, updating every second and returning the current count and any errors.
102
+
103
+ - **`useBattery`**: Monitors the battery status of the device, including level, charging status, and remaining charging or discharging time.
104
+
105
+ - **`useEventListener`**: 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.
106
+
107
+ - **`useHistory`**: Provides methods to navigate the browser history, including pushing and replacing history states, as well as moving back and forward in the history stack.
108
+
109
+ - **`usePreferredLanguage`**: Retrieves the user's preferred language and languages from the browser, and checks if the browser supports the language APIs.
110
+
111
+ - **`useSessionStorage`**: Stores and retrieves data from the `sessionStorage` API, persisting the data during the session. It provides a getter and setter for session-based data.
112
+
113
+ - **`useSound`**: Controls the playback of an audio file, including play, pause, and stop functionalities, while also managing the audio volume and handling any errors.
114
+
115
+ - **`useTouch`**: Tracks touch events on a given DOM element, returning the touch positions for `touchstart`, `touchmove`, and `touchend`.
116
+
117
+ - **`useUpdateEffect`**: Executes a side effect on updates after the initial render, skipping the effect during the first render to avoid unnecessary executions.
118
+
119
+ ## License
120
+
121
+ [MIT](https://opensource.org/licenses)
@@ -0,0 +1,195 @@
1
+ import * as react from 'react';
2
+ import { RefObject } from 'react';
3
+ import { AxiosRequestConfig } from 'axios';
4
+
5
+ interface UseAxiosResponse<T> {
6
+ data: T | null;
7
+ loading: boolean;
8
+ error: string | null;
9
+ makeRequest: (url: string, method?: string, requestData?: any) => void;
10
+ cancelRequest: () => void;
11
+ }
12
+ interface UseAxiosConfig extends AxiosRequestConfig {
13
+ baseURL?: string;
14
+ headers?: {
15
+ [key: string]: string;
16
+ };
17
+ }
18
+ declare const useAxios: <T>(config?: UseAxiosConfig) => UseAxiosResponse<T>;
19
+ declare const useAdvReducer: <State, Action extends {
20
+ type: string;
21
+ }>(initialState: State, actions: Record<string, (state: State, action: Action) => State>) => (state: State | undefined, action: Action) => State;
22
+ interface FetchState<T> {
23
+ data: T | null;
24
+ loading: boolean;
25
+ error: string | null;
26
+ }
27
+ declare function useFetch<T>(url: string): FetchState<T>;
28
+ declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void];
29
+ declare function useToggle(initialValue?: boolean): [boolean, () => void];
30
+ declare function useDebounce<T>(value: T, delay: number): T;
31
+ declare function useThrottle<T>(value: T, limit: number): T;
32
+ declare function usePrevious<T>(value: T): T | undefined;
33
+ declare function useMediaQuery(query: string): boolean;
34
+ declare function useClipboard(): [boolean, (text: string) => Promise<void>];
35
+ declare function useInterval(callback: () => void, delay: number | null): void;
36
+ interface WindowSize {
37
+ width: number;
38
+ height: number;
39
+ }
40
+ declare function useWindowSize(): WindowSize;
41
+ declare function useKeyPress(targetKey: string): boolean;
42
+ declare function useOnlineStatus(): boolean;
43
+ interface ScrollPosition {
44
+ x: number;
45
+ y: number;
46
+ }
47
+ declare function useScrollPosition(): ScrollPosition;
48
+ declare function useTimeout(callback: () => void, delay: number | null): void;
49
+ declare function useDarkMode(): [boolean, () => void];
50
+ declare function useForm<T extends Record<string, any>>(initialValues: T): {
51
+ values: T;
52
+ errors: Partial<Record<keyof T, string>>;
53
+ handleChange: (name: keyof T, value: any) => void;
54
+ validate: (validators: Partial<Record<keyof T, (value: any) => string | null>>) => boolean;
55
+ };
56
+ declare function useArray<T>(initialArray: T[]): {
57
+ array: T[];
58
+ set: react.Dispatch<react.SetStateAction<T[]>>;
59
+ push: (item: T) => void;
60
+ removeByIndex: (index: number) => void;
61
+ clear: () => void;
62
+ };
63
+ declare function useStep<T>(steps: T[]): {
64
+ currentStep: T;
65
+ currentStepIndex: number;
66
+ next: () => void;
67
+ previous: () => void;
68
+ reset: () => void;
69
+ isFirstStep: boolean;
70
+ isLastStep: boolean;
71
+ };
72
+ declare function useTimeoutFn(callback: () => void, delay: number | null): {
73
+ reset: () => void;
74
+ clear: () => void;
75
+ };
76
+ declare function useDebouncedCallback(callback: () => void, delay: number): () => void;
77
+ declare function useScrollLock(lock: boolean): void;
78
+ declare function useResizeObserver<T extends HTMLElement>(ref: RefObject<T>): WindowSize | null;
79
+ interface MousePosition {
80
+ x: number;
81
+ y: number;
82
+ }
83
+ declare function useMousePosition(): MousePosition;
84
+ type ScrollDirection = 'up' | 'down';
85
+ declare function useScrollDirection(): ScrollDirection;
86
+ declare function useImageLoader(src: string): {
87
+ loaded: boolean;
88
+ error: boolean;
89
+ };
90
+ declare function usePersistedState<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>];
91
+ declare function useReducedMotion(): boolean;
92
+ declare function useCookie(key: string): [string | null, (value: string, options?: any) => void, () => void];
93
+ declare function useFetchRetry<T>(url: string, options: RequestInit, retries?: number): {
94
+ data: T | null;
95
+ error: string | null;
96
+ loading: boolean;
97
+ };
98
+ declare function useDelay<T>(value: T, delay: number): T;
99
+ declare function useVisibilityChange(): boolean;
100
+ declare function useDebouncedValue<T>(value: T, delay: number): T;
101
+ type Status = 'idle' | 'pending' | 'success' | 'error';
102
+ type AsyncFunction<T> = () => Promise<T>;
103
+ interface UseAsyncReturn<T> {
104
+ execute: () => void;
105
+ status: Status;
106
+ value: T | null;
107
+ error: Error | null;
108
+ }
109
+ declare function useAsync<T>(asyncFunction: AsyncFunction<T>, immediate?: boolean): UseAsyncReturn<T>;
110
+ type ScriptStatus = 'loading' | 'ready' | 'error' | 'unknown';
111
+ declare function useScript(src: string, removeOnUnmount?: boolean): ScriptStatus;
112
+ declare function useIndexedDB<T>(dbName: string, storeName: string): {
113
+ data: T | null;
114
+ error: Error | null;
115
+ };
116
+ declare function useGeoLocation(): {
117
+ position: GeolocationPosition | null;
118
+ error: Error | null;
119
+ };
120
+ declare function useTimer(initialTime: number): {
121
+ time: number;
122
+ error: Error | null;
123
+ };
124
+ declare function useIsMounted(): boolean;
125
+ declare function useCss(css: string): {
126
+ error: Error | null;
127
+ };
128
+ declare function useSpeak(text: string): {
129
+ speak: () => void;
130
+ error: Error | null;
131
+ };
132
+ declare function useCountUp(target: number, duration: number): {
133
+ count: number;
134
+ error: Error | null;
135
+ };
136
+ declare function useCountDown(start: number): {
137
+ count: number;
138
+ error: Error | null;
139
+ };
140
+ interface BatteryState {
141
+ supported: boolean;
142
+ loading: boolean;
143
+ level: number | null;
144
+ charging: boolean | null;
145
+ chargingTime: number | null;
146
+ dischargingTime: number | null;
147
+ }
148
+ declare const useBattery: () => BatteryState;
149
+ declare const useEventListener: (eventName: string, handler: (event: Event) => void, elementRef?: React.RefObject<HTMLElement>, options?: boolean | AddEventListenerOptions) => void;
150
+ interface HistoryState {
151
+ [key: string]: any;
152
+ }
153
+ interface UseHistory {
154
+ history: History;
155
+ state: HistoryState | null;
156
+ push: (path: string, state?: HistoryState) => void;
157
+ replace: (path: string, state?: HistoryState) => void;
158
+ goBack: () => void;
159
+ goForward: () => void;
160
+ }
161
+ declare const useHistory: () => UseHistory;
162
+ interface UsePreferredLanguage {
163
+ language: string;
164
+ languages: Array<string>;
165
+ isSupported: boolean;
166
+ }
167
+ declare const usePreferredLanguage: () => UsePreferredLanguage;
168
+ interface UseSessionStorage<T> {
169
+ (key: string, initialValue: T): [T, (value: T) => void];
170
+ }
171
+ declare const useSessionStorage: UseSessionStorage<any>;
172
+ interface UseSound {
173
+ play: () => void;
174
+ pause: () => void;
175
+ stop: () => void;
176
+ setVolume: (volume: number) => void;
177
+ isPlaying: boolean;
178
+ error: Error | null;
179
+ }
180
+ declare const useSound: (url: string) => UseSound;
181
+ interface TouchPosition {
182
+ x: number | null;
183
+ y: number | null;
184
+ }
185
+ interface UseTouch {
186
+ (elementRef: React.RefObject<HTMLElement>): {
187
+ touchStart: TouchPosition;
188
+ touchMove: TouchPosition;
189
+ touchEnd: TouchPosition;
190
+ };
191
+ }
192
+ declare const useTouch: UseTouch;
193
+ declare const useUpdateEffect: (effect: React.EffectCallback, deps: React.DependencyList) => void;
194
+
195
+ export { type AsyncFunction, type ScriptStatus, type Status, type UseAsyncReturn, useAdvReducer, useArray, useAsync, useAxios, useBattery, useClipboard, useCookie, useCountDown, useCountUp, useCss, useDarkMode, useDebounce, useDebouncedCallback, useDebouncedValue, useDelay, useEventListener, useFetch, useFetchRetry, useForm, useGeoLocation, useHistory, useImageLoader, useIndexedDB, useInterval, useIsMounted, useKeyPress, useLocalStorage, useMediaQuery, useMousePosition, useOnlineStatus, usePersistedState, usePreferredLanguage, usePrevious, useReducedMotion, useResizeObserver, useScript, useScrollDirection, useScrollLock, useScrollPosition, useSessionStorage, useSound, useSpeak, useStep, useThrottle, useTimeout, useTimeoutFn, useTimer, useToggle, useTouch, useUpdateEffect, useVisibilityChange, useWindowSize };