
**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.

**Note : This lightweight and type-safe package is written in TypeScript and offers full support for all hooks across all modern browsers.**

### Installation

Install the package:

```bash
npm install react-hook-toolkit
# or
pnpm add react-hook-toolkit
```

### **Authors**

![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)

### **Browser Support**  

| ![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)
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Latest ✔                                                                                          | Latest ✔                                                                                             | Latest ✔                                                                                          | Latest ✔                                                                                       | Latest ✔                                                                                    | 


###  **Features**
Here's the properly structured documentation with clear purpose explanations:

------------------------------------------ **Custom Hooks**  ------------------------------------------------

📌 **useBrowser**  
Provides comprehensive browser control and environment detection with a unified API for navigation, window management, and system interactions.

```ts
const {
    goBack,
    goForward,
    reload,
    navigateTo,
    clearBrowserData,
    historyState,
    isOnline,
    copyCurrentUrl,
    openNewTab,
    isFullscreen,
    isShareSupported,
    closeCurrentTab
  } = useBrowser();
```

📌 **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.
```ts
const { data, loading, error, makeRequest, cancelRequest } = useAxios({ baseURL: '/api' });

useEffect(() => {
  makeRequest('/users', 'GET');
}, []);
```
---
📌 **useRequest**  
Provides an easy way to fetch data with hooks, managing loading, data, and error states.

```ts
const { data, loading, error } = useRequest('/api/data');
```
---
  📌 **useRequestRetry**  
Performs an HTTP request with retry logic, retrying a specified number of times upon failure before returning an error.

```ts
const { data, loading, error } = useRequestRetry('/api/user', { method: 'GET' }, 3);
```
---
  📌 **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.

```ts
const { execute, status, value, error } = useAsync(fetchUser);

execute(); // ➝ runs the async function
```
---
  📌 **useDebounce**  
Delays updating the state until after a specified delay, useful for preventing frequent updates (e.g., handling user input).

```ts
const debouncedSearch = useDebounce(searchText, 500);
```

---
  📌 **useDebouncedCallback**  
Delays the execution of a callback function until after a specified delay, resetting the delay on each call to prevent frequent execution.

```ts
const debounced = useDebouncedCallback(() => search(input), 300);

input.onChange = debounced;
```
---
📌 **useDebouncedValue**  
Returns a debounced version of a value.

```ts
const debouncedValue = useDebouncedValue(value, 300);
```
---
  📌 **useThrottle**  
Limits how often a value updates within a given time interval, useful for performance optimization.

```ts
const throttledScroll = useThrottle(scrollValue, 300);
```

---
  📌 **useDelay**  
Delays the update of a value for a specified amount of time before reflecting it in the state.

```ts
const delayedValue = useDelay(value, 500);
```
---
  📌 **useTimer**  
Starts a countdown timer that updates the time every second, returning the current time and any errors.

```ts
const { time, error } = useTimer(60); // starts from 60 and counts down
```
---
  📌 **useInterval**  
Runs a callback function at a specified time interval and clears it when the delay is null or the component unmounts.

```ts
useInterval(() => {
  console.log('Tick');
}, 1000);
```
---
  📌 **useTimeout**  
Executes a function after a specified delay and cleans up automatically when dependencies change.

```ts
useTimeout(() => {
  console.log('Time\'s up!');
}, 2000);
```

---

  📌 **useForm**  
Manages form state, handles input changes, and performs validation using provided validators.

```ts
const { values, errors, handleChange, validate } = useForm({ name: '', email: '' });

handleChange('name', 'John');

validate({
  name: (val) => (!val ? 'Required' : null),
  email: (val) => (!val.includes('@') ? 'Invalid email' : null),
});
```
---
📌 **useFormSubmit**  
 Handles form submission with loading/error states and success callbacks.

```ts
const { submit, isLoading, error } = useFormSubmit(apiCall, {
  onSuccess: (data) => console.log('Saved!', data)
});

// Example
submit(formData);
```
---
📌 **useSmartForm**  
 Complete form management with validation, submission, and state handling.

```ts
const { register, handleSubmit, errors } = useSmartForm({
  initialValues,
  validationSchema,
  onSubmit: (data) => console.log(data)
});

// Example
<input {...register('email') />
<button onClick={handleSubmit}>Save</button>
```
---
📌 **useCrossFieldValidation**  
 Handles complex validation rules that depend on multiple fields.

```ts
const { errors, validate } = useCrossFieldValidation({
  rules: {
    password: (val, { confirmPassword }) => val === confirmPassword,
  },
  initialValues
});

// Example
validate('password', 'secret123', { confirmPassword: 'secret123' });
```

---

📌 **useFieldArray**  
 Manages dynamic arrays of form fields with add/remove/reorder operations.

```ts
const { fields, append, remove, move } = useFieldArray(initialItems);

// Example
append({ name: '', email: '' });
remove(0); // Remove first item
move(1, 0); // Move second item to first position
```
---
📌 **useFormWizard**  
 Manages multi-step forms with navigation between steps.

```ts
const { currentStep, next, prev, goto } = useFormWizard(steps.length);

// Example
next(); // Move to next step
goto(3); // Jump to step 4
```

---
 📌 **usePersistedForm**  
 Automatically persists form state to localStorage/sessionStorage and restores it on page reload.

```ts
const { values, setField, reset } = usePersistedForm('form-key', initialValues);

// Example
setField('username', 'john_doe'); // Auto-saves to storage
reset(); // Clears storage
```


---

  📌 **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.

```ts
useEventListener('resize', (e) => {
  console.log('Window resized');
});
```
---
📌 **useEventListeners**  
 Simplifies adding/removing event listeners.

```ts
useEventListeners({
  click: handleClick,
  resize: handleResize
});

// Example
useEventListeners({
  keydown: (e) => console.log(e.key)
});
```
---
  📌 **useKeyPress**  
Detects whether a specific key is being pressed or released.

```ts
const isEnterPressed = useKeyPress('Enter');
```
---
📌 **useLongPress**  
 Detects long press gestures.

```ts
const handlers = useLongPress(() => console.log('Long pressed!'), {
  threshold: 1000
});

// Example
<button {...handlers}>Hold me</button>
```
---
  📌 **useTouch**  
Tracks touch events on a given DOM element, returning the touch positions for `touchstart`, `touchmove`, and `touchend`.

```ts
const ref = useRef(null);
const {
  touchStart,
  touchMove,
  touchEnd
} = useTouch(ref);

<div ref={ref}>Swipe here</div>
```
---
📌 **useIdle**  
 Detects when user becomes inactive.

```ts
const isIdle = useIdle(30000); // 30s timeout

// Example
{isIdle && <ScreenSaver />}
```
---
📌 **useDragReorder**  
 Enables drag-and-drop reordering of lists.

```ts
const { items, dragStart, dragOver, drop } = useDragReorder(initialItems);

// Example
<div 
  draggable 
  onDragStart={() => dragStart(index)}
  onDragOver={() => dragOver(index)}
  onDrop={drop}
/>
```

---

  📌 **useToggle**  
A simple boolean toggle hook that returns a state and a function to toggle its value.

```ts
const [isOpen, toggle] = useToggle(false);
```
---
  📌 **useArray**
Provides an array state with helper functions to manipulate it, including setting, adding, removing by index, and clearing elements.

```ts
const { array, set, push, removeByIndex, clear } = useArray([1, 2, 3]);

push(4);            // ➝ [1, 2, 3, 4]
removeByIndex(1);   // ➝ [1, 3, 4]
clear();            // ➝ []
```
---
  📌 **useStepper**  
Manages step-based navigation by keeping track of the current step index and providing functions to move forward, backward, and reset.

```ts
const { activeStep, handleNext, handleBack, handleReset, isFirstStep, isLastStep } = useStepper(5);

handleNext(); // ➝ advances step
handleBack(); // ➝ goes back
handleReset(); // ➝ step 0
```

📌 **useDrawer**
Provides global drawer state and controls to open/close the drawer and manage the current selected main menu, including support for button-triggered toggling.

```ts
const {
  drawerOpen,              
  openDrawer,              
  closeDrawer,            
  openDrawerInButton,      
  closeDrawerInButton,     
  currentMainMenu,
  setCurrentMainMenu,  
} = useContext();
```

---
📌 **useUndo**  
 Provides undo/redo functionality for state changes.

```ts
const { state, setState, undo, redo } = useUndo(initialState);

// Example
setState({ items: [...] });
undo(); // Reverts to previous state
```
---
  📌 **useGenericReducer**  
A custom reducer function that takes an `initialState` and an object of actions, returning a new state based on the action type. 

```ts
const reducer = useGenericReducer(initialState, {
  increment: (state) => ({ count: state.count + 1 }),
});
const [state, dispatch] = useReducer(reducer, initialState);
```
---
  📌 **useIsMounted**  
Tracks whether the component is mounted or unmounted, returning a boolean value indicating the component's mount status.

```ts
const isMounted = useIsMounted();
```
---
📌 **useIsFirstRender**  
 Returns true only on component's first render.

```ts
const isFirst = useIsFirstRender();

// Example
useEffect(() => {
  if (!isFirst) console.log('Updated!');
}, [deps]);
```
---
📌 **usePrevious**  
Tracks the previous value of a state or prop.

```ts
const previousValue = usePrevious(currentValue);
```
---
  📌 **useUpdateEffect**  
Executes a side effect on updates after the initial render, skipping the effect during the first render to avoid unnecessary executions.

```ts
useUpdateEffect(() => {
  console.log("This runs only on updates.");
}, [value]);
```
---

📌 **useList**  
 Manages array state with utility methods.

```ts
const { list, push, remove, update } = useList(initialItems);

// Example
push(newItem);
remove(0); // Remove first item
```

---

  📌 **useLocalStorage**  
 A hook to persist state in `localStorage`. It initializes state from `localStorage` and updates it whenever the value changes.

```ts
const [token, setToken] = useLocalStorage('authToken', '');
```
---
  📌 **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.

```ts
const [value, setValue] = useSessionStorage("myKey", "default");

setValue("newValue");
console.log(value);
```

---
  📌 **useCookie**  
Manages cookies by providing functions to get, set, and delete a specific cookie by its key.

```ts
const [token, setToken, deleteToken] = useCookie('token');

setToken('abc123');
deleteToken();
```
---
  📌 **usePersistedState**  
Stores and retrieves state from `localStorage` to persist data across page reloads.

```ts
const [theme, setTheme] = usePersistedState('theme', 'light');
```
---
  📌 **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.

```ts
const {
  history,
  state,
  push,
  replace,
  goBack,
  goForward
} = useHistory();

push('/about', { from: 'home' });
replace('/profile');
goBack();
goForward();
```

---
📌 **useRecentSearch**  
 Return and manage recent searched history.

```ts
  const { recentSearches, addSearch, clearSearch, hasSearch } = useRecentSearch<SearchItem>({
    key: 'myRecentItems',
    limit: 5,
    uniqueKey: 'id',
    excludeEmpty: true,
  });

```
---
📌 **useHistoryState**  
 Manages state history with undo/redo capabilities.

```ts
const { state, setState, undo, redo } = useHistoryState(initialState);

// Example
setState({...});
undo(); // Reverts change
```
---
  📌 **useVisibilityChange**  
Tracks the visibility state of the document and returns whether the page is currently visible or hidden.

```ts
const isVisible = useVisibilityChange(); // ➝ true | false
```
---
📌 **useDarkMode**  
Detects and manages dark mode preferences in the browser.

```ts
const [isDarkMode, toggleDarkMode] = useDarkMode();
```
---
📌 **usePreferredLanguage**  
Detects the preferred language set in the browser.

```ts
const language = usePreferredLanguage();
```
---
📌 **useIndexedDB**  
Provides a hook to interact with IndexedDB in the browser, enabling persistent client-side storage.

```ts
const { data, setData } = useIndexedDB('dbName');
```
---

📌 **useMediaQuery**  
Checks if a media query condition matches the current viewport, useful for responsive design.

```ts
const isMobile = useMediaQuery('(max-width: 768px)');
```
---
📌 **useWindowSize**  
Returns the current window size (width and height).

```ts
const { width, height } = useWindowSize();
```
---
  📌 **useResizeObserver**  
Observes and returns the dimensions of an HTML element using the `ResizeObserver` API.

```ts
const size = useResizeObserver(ref);

// size = { width: 200, height: 100 }
```
---
  📌 **useScrollPosition**  
Tracks the horizontal (x) and vertical (y) scroll positions of the window.

```ts
const { x, y } = useScrollPosition();
```
---
  📌 **useScrollDirection**  
Determines whether the user is scrolling up or down based on window scroll position changes.

```ts
const direction = useScrollDirection(); // ➝ 'up' | 'down'
```

📌 **useScrollLock**  
Locks or unlocks scrolling on the page.

```ts
useScrollLock(true); // Lock scrolling
useScrollLock(false); // Unlock scrolling
```
---
📌 **useLockBodyScroll**  
Prevents scrolling on the body element, useful for modals or off-canvas menus.

```ts
useLockBodyScroll(true);
```
---
📌 **useCss**  
Allows injecting dynamic CSS rules into the document.

```ts
useCss('.class { color: red; }');
```
---
📌 **useReducedMotion**  
Detects whether the user has reduced motion settings in their OS preferences.

```ts
const prefersReducedMotion = useReducedMotion();
```
---
📌 **useImageLoader**  
Provides a way to load and display images in a way that improves performance and loading behavior.

```ts
const { isLoading, image } = useImageLoader('imageURL');
```

---

  📌 **useBattery**  
 Monitors the battery status of the device, including level, charging status, and remaining charging or discharging time.

```ts
const { level, charging, supported, loading, chargingTime, dischargingTime } = useBattery();
```
---
  📌 **useGeoLocation**  
Retrieves the user's current geographic location and returns it along with any error encountered.

```ts
const { position, error } = useGeoLocation();
```
---
  📌 **useMousePosition**  
Tracks the user's mouse position in real-time and returns the coordinates. 

```ts
const { x, y } = useMousePosition();
```

---
  📌 **useOnlineStatus**  
Monitors the user's network connection status (online/offline).

```ts
const isOnline = useOnlineStatus();
```

---

  📌 **useSound**  
Controls the playback of an audio file, including play, pause, and stop functionalities, while also managing the audio volume and handling any errors.

```ts
const {
  play,
  pause,
  stop,
  setVolume,
  isPlaying,
  error
} = useSound("/sound.mp3");

play();
pause();
stop();
setVolume(0.5);
```
---
  📌 **useSpeak**  
Converts text to speech using the Web Speech API, allowing the text to be spoken and handling errors.
```ts
const { speak, error } = useSpeak('Hello world!');
speak();
```
---

### 📌 **usePermission**  
Monitors the status of a specific browser permission (like geolocation, camera, microphone, etc.) and updates reactively when the permission state changes.

```ts
const permission = usePermission({ name: 'geolocation' });
```

---

### 📌 **usePageLeave**  
Detects when the mouse leaves the viewport (commonly used to detect exit intent on websites).

```ts
usePageLeave(() => {
  console.log('Mouse left the page');
});
```

---

### 📌 **useMotion**  
Subscribes to device motion events (like `acceleration` or `rotation`) and returns the latest motion values from sensors on mobile devices.

```ts
const motion = useMotion();
console.log(motion.acceleration);
```

---

### 📌 **useHoverDirty**  
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.

```ts
const ref = useRef(null);
const isHovered = useHoverDirty(ref);
```

---

### 📌 **useBeforeUnload**  
Prompts the user with a confirmation dialog before leaving the page (refresh, close tab, etc.).

```ts
useBeforeUnload(true); // Triggers default browser dialog
```

---

### 📌 **useClickAway**  
Triggers a handler function when a user clicks outside of a specified element.

```ts
const ref = useRef(null);
useClickAway(ref, () => {
  console.log('Clicked outside');
});
```

---

### 📌 **useResponsive**  
Tracks screen size and returns breakpoint-based flags (`xs`, `sm`, `md`, etc.) to help in building responsive UI layouts.

```ts
const screens = useResponsive();
console.log(screens.md); // true or false
```

---

### 📌 **useUnmountedRef**  
Returns a `ref` that indicates whether the component is currently unmounted—useful to prevent state updates on unmounted components.

```ts
const unmountedRef = useUnmountedRef();
```
---
  📌 **useCountUp**  
 Animates a counter that counts up from 0 to a target value within a specified duration, returning the current count and any errors.

```ts
const { count, error } = useCountUp(100, 5000); // counts up to 100 in 5s
```

---
  📌 **useCountDown**  
Counts down from a specified start value to zero, updating every second and returning the current count and any errors.

```ts
const { count, error } = useCountDown(10); // counts down from 10
```

---

📌 **useWebSocket**  
 Manages WebSocket connections with auto-reconnect.

```ts
const { send, message, status } = useWebSocket('ws://api.example.com');

// Example
send(JSON.stringify({ action: 'ping' }));
```
---

Let me know if you'd like more information or changes!

------------------------------------- **Custom Components** --------------------------------------------

  ✅ **DynamicLoader**  
A Higher-Order Component (HOC) that dynamically loads a React component using `React.lazy()` with `Suspense`, while wrapping it in an `ErrorBoundary` to handle potential errors gracefully. It ensures that the component is loaded only when needed, reducing the initial bundle size and improving performance.

```jsx
import React, { lazy } from "react";
const MyComponent = DynamicLoader(lazy(() => import("./MyComponent")));

```
---

✅ **ContextMenuWrapper**  
Displays a customizable context menu with support for light/dark themes, keyboard navigation, accessibility compliance, and automatic positioning. Handles items, dividers, icons, shortcuts, and click events.

```tsx
<ContextMenuWrapper
  options={[
    { label: 'Edit', icon: <EditIcon />, onClick: handleEdit },
    { label: 'Copy', shortcut: '⌘C', onClick: handleCopy },
    'divider',
    { label: 'Delete', disabled: true, onClick: handleDelete }
  ]}
  theme="dark"
  onShow={() => console.log('Menu opened')}
  onHide={() => console.log('Menu closed')}
  currentInstance={this}
>
  <div>Right-click here</div>
</ContextMenu>
```

✅ **AnimatedWrapper**
A lightweight wrapper component that applies animations to its children with customizable animation type and delay.Ideal for enhancing UI transitions smoothly.

```tsx
<AnimatedWrapper animationClass="animate__fadeIn" delay={1}>
  <div>Hello with delay</div>
</AnimatedWrapper>
```

✅ **RichTextEditor**  
Provides a fully-featured WYSIWYG editor with HTML conversion, customizable toolbar, and responsive design for rich text input.

```tsx
<RichTextEditor 
  initialHtml="<p>Initial content</p>"
  onChange={(html) => console.log(html)}
  placeholder="Type your text here..."
  minHeight="300px"
/>
```

---
  ✅ **FilePreview**  
Displays a styled file card with an icon based on file type, filename with ellipsis handling, file size, and an optional download action.

```tsx
<FilePreview
  primaryKey="file123"
  filename="example.pdf"
  size="2.3 MB"
  onDownload={(id) => console.log("Download:", id)}
/>
```
---
 ✅ **UploadFile**  
Renders an icon button for file uploads with visual feedback for different upload states (loading, success, error). It supports disabling, color customization, and a hidden file input for seamless UX.

```tsx
<UploadFile
  isUpload={true}
  color="#1976d2"
  state={{
    isUploaded: false,
    isUploadError: false,
    isLoadingUpload: true,
  }}
  onFileSelect={(file) => console.log(file)}
/>

const handleFileSelect = async (files: any) => {
  setState({ isUploaded: false, isUploadError: false, isLoadingUpload: true });
  try {
    await _promise(2000);
    setState({ isUploaded: true, isUploadError: false, isLoadingUpload: false });
  } catch (err) {
    setState({ isUploaded: false, isUploadError: true, isLoadingUpload: false });
  }
};
```
---

 ✅ **DownloadFile**  
Renders an icon button for file downloads with visual feedback for different states (loading, success, error). It supports color customization and disables interaction during loading.

```tsx
<DownloadFile
  isDownload={true}
  color="primary"
  state={{
    isDownloaded: false,
    isDownloadError: false,
    isLoadingDownload: true,
  }}
  onDownload={() => console.log('Download initiated')}
 />
```

---

 ✅ **LabeledValue**  
Displays a simple key-value label pair in a single line, with optional styling.

```tsx
<LabeledValue
  label="Name"
  value="ABC"
/>
```
---

 ✅ **DetailsCard**  
Renders a card with a title and grid-based layout of labeled values. It supports custom spacing, responsive behavior, and optional card shadow.

```tsx
<DetailsCard
  title="Details"
  spacing={2}
  details={[
    { label: 'Name', value: 'XYZ' },
  ]}
/>
```

---
  ✅ **AlertMessage**  
A functional React component that displays dynamic alerts using the enqueueSnackbar function. It provides a customizable message with a specified type and duration. The alerts can be dismissed manually by clicking a close button, and they support various configurations such as position, auto-hide duration, and duplicate prevention.

```jsx
<AlertMessage type="success" msg="Data saved successfully!" />
```
---
  ✅ **FieldSkeleton**  
Simulates form field placeholders with optional label skeletons, useful for loading states in forms or input sections.

```jsx
<FieldSkeleton 
  length={3} 
  spacing={2} 
  isLabel={true} 
  responsive={{ xs: 12, sm: 6, md: 4 }} 
/>
```
---

 ✅ **FileSkeleton**  
Displays one or more placeholder file cards mimicking the layout of file previews. Useful during file list loading.

```tsx
<FileSkeleton
  length={3}
  width={350}
  borderColor="#dfdfdf"
/>
```

---

 ✅ **TableSkeleton**  
Shows a full table layout with skeleton headers and rows. Includes a toolbar area for filters or search bars.

```tsx
<TableSkeleton
  rows={6}
  columns={6}
/>
```

---

 ✅ **CardSkeleton**  
Simulates a card layout with a title and multiple row placeholders, ideal for stat or summary cards.

```tsx
<CardSkeleton />
```

---

 ✅ **LineChartSkeleton**  
Represents a placeholder for a line chart with gridlines and axis lines to simulate loading of chart data.

```tsx
<LineChartSkeleton />
```

---

 ✅ **PieChartSkeleton**  
Displays a skeleton placeholder for a pie chart inside a card layout. Includes a title and circular loading element.

```tsx
<PieChartSkeleton />
```

---

  **License** 

[MIT](https://docs.npmjs.com/policies/npm-license) © (2022-2024)
