react-hook-toolkit 0.0.4 → 0.0.6

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,126 @@
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
+ ## Authors
120
+
121
+ - **Shivaji** : (Sr. React Developer)
122
+ - **Shyamal** : (Sr. React Developer)
123
+
124
+ ## License
125
+
126
+ [MIT](https://opensource.org/licenses)
@@ -0,0 +1,192 @@
1
+ import { RefObject } from 'react';
2
+ import { AxiosRequestConfig } from 'axios';
3
+ interface UseAxiosResponse<T> {
4
+ data: T | null;
5
+ loading: boolean;
6
+ error: string | null;
7
+ makeRequest: (url: string, method?: string, requestData?: any) => void;
8
+ cancelRequest: () => void;
9
+ }
10
+ interface UseAxiosConfig extends AxiosRequestConfig {
11
+ baseURL?: string;
12
+ headers?: {
13
+ [key: string]: string;
14
+ };
15
+ }
16
+ export declare const useAxios: <T>(config?: UseAxiosConfig) => UseAxiosResponse<T>;
17
+ export declare const useAdvReducer: <State, Action extends {
18
+ type: string;
19
+ }>(initialState: State, actions: Record<string, (state: State, action: Action) => State>) => (state: State | undefined, action: Action) => State;
20
+ interface FetchState<T> {
21
+ data: T | null;
22
+ loading: boolean;
23
+ error: string | null;
24
+ }
25
+ export declare function useFetch<T>(url: string): FetchState<T>;
26
+ export declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void];
27
+ export declare function useToggle(initialValue?: boolean): [boolean, () => void];
28
+ export declare function useDebounce<T>(value: T, delay: number): T;
29
+ export declare function useThrottle<T>(value: T, limit: number): T;
30
+ export declare function usePrevious<T>(value: T): T | undefined;
31
+ export declare function useMediaQuery(query: string): boolean;
32
+ export declare function useClipboard(): [boolean, (text: string) => Promise<void>];
33
+ export declare function useInterval(callback: () => void, delay: number | null): void;
34
+ interface WindowSize {
35
+ width: number;
36
+ height: number;
37
+ }
38
+ export declare function useWindowSize(): WindowSize;
39
+ export declare function useKeyPress(targetKey: string): boolean;
40
+ export declare function useOnlineStatus(): boolean;
41
+ interface ScrollPosition {
42
+ x: number;
43
+ y: number;
44
+ }
45
+ export declare function useScrollPosition(): ScrollPosition;
46
+ export declare function useTimeout(callback: () => void, delay: number | null): void;
47
+ export declare function useDarkMode(): [boolean, () => void];
48
+ export declare function useForm<T extends Record<string, any>>(initialValues: T): {
49
+ values: T;
50
+ errors: Partial<Record<keyof T, string>>;
51
+ handleChange: (name: keyof T, value: any) => void;
52
+ validate: (validators: Partial<Record<keyof T, (value: any) => string | null>>) => boolean;
53
+ };
54
+ export declare function useArray<T>(initialArray: T[]): {
55
+ array: T[];
56
+ set: import("react").Dispatch<import("react").SetStateAction<T[]>>;
57
+ push: (item: T) => void;
58
+ removeByIndex: (index: number) => void;
59
+ clear: () => void;
60
+ };
61
+ export declare function useStep<T>(steps: T[]): {
62
+ currentStep: T;
63
+ currentStepIndex: number;
64
+ next: () => void;
65
+ previous: () => void;
66
+ reset: () => void;
67
+ isFirstStep: boolean;
68
+ isLastStep: boolean;
69
+ };
70
+ export declare function useTimeoutFn(callback: () => void, delay: number | null): {
71
+ reset: () => void;
72
+ clear: () => void;
73
+ };
74
+ export declare function useDebouncedCallback(callback: () => void, delay: number): () => void;
75
+ export declare function useScrollLock(lock: boolean): void;
76
+ export declare function useResizeObserver<T extends HTMLElement>(ref: RefObject<T>): WindowSize | null;
77
+ interface MousePosition {
78
+ x: number;
79
+ y: number;
80
+ }
81
+ export declare function useMousePosition(): MousePosition;
82
+ type ScrollDirection = 'up' | 'down';
83
+ export declare function useScrollDirection(): ScrollDirection;
84
+ export declare function useImageLoader(src: string): {
85
+ loaded: boolean;
86
+ error: boolean;
87
+ };
88
+ export declare function usePersistedState<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>];
89
+ export declare function useReducedMotion(): boolean;
90
+ export declare function useCookie(key: string): [string | null, (value: string, options?: any) => void, () => void];
91
+ export declare function useFetchRetry<T>(url: string, options: RequestInit, retries?: number): {
92
+ data: T | null;
93
+ error: string | null;
94
+ loading: boolean;
95
+ };
96
+ export declare function useDelay<T>(value: T, delay: number): T;
97
+ export declare function useVisibilityChange(): boolean;
98
+ export declare function useDebouncedValue<T>(value: T, delay: number): T;
99
+ export type Status = 'idle' | 'pending' | 'success' | 'error';
100
+ export type AsyncFunction<T> = () => Promise<T>;
101
+ export interface UseAsyncReturn<T> {
102
+ execute: () => void;
103
+ status: Status;
104
+ value: T | null;
105
+ error: Error | null;
106
+ }
107
+ export declare function useAsync<T>(asyncFunction: AsyncFunction<T>, immediate?: boolean): UseAsyncReturn<T>;
108
+ export type ScriptStatus = 'loading' | 'ready' | 'error' | 'unknown';
109
+ export declare function useScript(src: string, removeOnUnmount?: boolean): ScriptStatus;
110
+ export declare function useIndexedDB<T>(dbName: string, storeName: string): {
111
+ data: T | null;
112
+ error: Error | null;
113
+ };
114
+ export declare function useGeoLocation(): {
115
+ position: GeolocationPosition | null;
116
+ error: Error | null;
117
+ };
118
+ export declare function useTimer(initialTime: number): {
119
+ time: number;
120
+ error: Error | null;
121
+ };
122
+ export declare function useIsMounted(): boolean;
123
+ export declare function useCss(css: string): {
124
+ error: Error | null;
125
+ };
126
+ export declare function useSpeak(text: string): {
127
+ speak: () => void;
128
+ error: Error | null;
129
+ };
130
+ export declare function useCountUp(target: number, duration: number): {
131
+ count: number;
132
+ error: Error | null;
133
+ };
134
+ export declare function useCountDown(start: number): {
135
+ count: number;
136
+ error: Error | null;
137
+ };
138
+ interface BatteryState {
139
+ supported: boolean;
140
+ loading: boolean;
141
+ level: number | null;
142
+ charging: boolean | null;
143
+ chargingTime: number | null;
144
+ dischargingTime: number | null;
145
+ }
146
+ export declare const useBattery: () => BatteryState;
147
+ export declare const useEventListener: (eventName: string, handler: (event: Event) => void, elementRef?: React.RefObject<HTMLElement>, options?: boolean | AddEventListenerOptions) => void;
148
+ interface HistoryState {
149
+ [key: string]: any;
150
+ }
151
+ interface UseHistory {
152
+ history: History;
153
+ state: HistoryState | null;
154
+ push: (path: string, state?: HistoryState) => void;
155
+ replace: (path: string, state?: HistoryState) => void;
156
+ goBack: () => void;
157
+ goForward: () => void;
158
+ }
159
+ export declare const useHistory: () => UseHistory;
160
+ interface UsePreferredLanguage {
161
+ language: string;
162
+ languages: Array<string>;
163
+ isSupported: boolean;
164
+ }
165
+ export declare const usePreferredLanguage: () => UsePreferredLanguage;
166
+ interface UseSessionStorage<T> {
167
+ (key: string, initialValue: T): [T, (value: T) => void];
168
+ }
169
+ export declare const useSessionStorage: UseSessionStorage<any>;
170
+ interface UseSound {
171
+ play: () => void;
172
+ pause: () => void;
173
+ stop: () => void;
174
+ setVolume: (volume: number) => void;
175
+ isPlaying: boolean;
176
+ error: Error | null;
177
+ }
178
+ export declare const useSound: (url: string) => UseSound;
179
+ interface TouchPosition {
180
+ x: number | null;
181
+ y: number | null;
182
+ }
183
+ interface UseTouch {
184
+ (elementRef: React.RefObject<HTMLElement>): {
185
+ touchStart: TouchPosition;
186
+ touchMove: TouchPosition;
187
+ touchEnd: TouchPosition;
188
+ };
189
+ }
190
+ export declare const useTouch: UseTouch;
191
+ export declare const useUpdateEffect: (effect: React.EffectCallback, deps: React.DependencyList) => void;
192
+ export {};