New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

react-hookstack

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-hookstack - npm Package Compare versions

Comparing version
1.0.4
to
1.0.5
+31
dist/hooks/browser/useCopyToClipboard.d.ts
/**
* @file useCopyToClipboard.ts
* @description A React hook to copy text to the clipboard with success feedback.
*
* @example
* const { copy, value, success } = useCopyToClipboard();
*
* <button onClick={() => copy("Hello World!")}>
* {success ? "Copied!" : "Copy Text"}
* </button>
*/
export interface UseCopyToClipboardReturn {
/** The last copied value */
value: string | null;
/** Whether the last copy attempt was successful */
success: boolean;
/** Copies the given text to the clipboard */
copy: (text: string) => Promise<boolean>;
/** Resets the state */
reset: () => void;
}
/**
* A hook that provides clipboard copy functionality.
*
* It supports both the modern Clipboard API and falls back to
* `document.execCommand` for older browsers.
*
* @returns An object with `copy`, `value`, `success`, and `reset`.
*/
export declare function useCopyToClipboard(): UseCopyToClipboardReturn;
export default useCopyToClipboard;
/**
* @file useEventListener.ts
* @description A React hook for safely adding and cleaning up event listeners.
* Works for both window, document, or specific DOM elements.
*
* @example
* // Example: Listening to window resize
* useEventListener('resize', () => console.log('Window resized!'));
*
* // Example: Listening to key press
* useEventListener('keydown', (e) => {
* if (e.key === 'Escape') console.log('Escape pressed!');
* });
*/
/**
* Custom hook to attach an event listener to a target element (window by default).
*
* @param eventName - The name of the event to listen for (e.g., 'click', 'resize').
* @param handler - The event handler function.
* @param element - Optional target element (defaults to window).
*/
export declare function useEventListener<K extends keyof WindowEventMap>(eventName: K, handler: (event: WindowEventMap[K]) => void, element?: Window | Document | HTMLElement | null): void;
export default useEventListener;
/**
* useInput Hook
*
* Manages input value, validation, and change events.
*
* @param {string} initialValue - The initial value of the input field.
* @param {(value: string) => string | undefined} [validate] - Optional validation function that returns an error message.
*
* @returns {{
* value: string;
* error?: string;
* onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
* reset: () => void;
* setValue: React.Dispatch<React.SetStateAction<string>>;
* }}
*
* @example
* const name = useInput('', (val) => !val ? 'Name is required' : undefined);
*
* return (
* <div>
* <input {...name} placeholder="Enter your name" />
* {name.error && <span style={{ color: 'red' }}>{name.error}</span>}
* <button onClick={name.reset}>Reset</button>
* </div>
* );
*/
export declare function useInput(initialValue?: string, validate?: (value: string) => string | undefined): {
value: string;
error: string | undefined;
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
reset: () => void;
setValue: import('react').Dispatch<import('react').SetStateAction<string>>;
};
/**
* useMap Hook
*
* A React hook to manage a Map with helpful utility functions.
*
* @template K - Key type
* @template V - Value type
*
* @param initialEntries - Optional initial entries for the Map
*
* @returns {{
* map: Map<K, V>;
* set: (key: K, value: V) => void;
* get: (key: K) => V | undefined;
* remove: (key: K) => void;
* has: (key: K) => boolean;
* clear: () => void;
* reset: () => void;
* }}
*
* @example
* const { map, set, get, remove, clear } = useMap<string, number>([['a', 1]]);
*
* set('b', 2);
* console.log(map.get('a')); // 1
* remove('a');
* clear();
*/
export declare function useMap<K, V>(initialEntries?: readonly (readonly [K, V])[]): {
map: Map<K, V>;
set: (key: K, value: V) => void;
get: (key: K) => V | undefined;
remove: (key: K) => void;
has: (key: K) => boolean;
clear: () => void;
reset: () => void;
};
/**
* useOnlineStatus Hook
*
* Detects the user's current online/offline status and updates reactively.
*
* @returns boolean - true if the user is online, false if offline
*
* @example
* const isOnline = useOnlineStatus();
* console.log(isOnline ? "🟢 Online" : "🔴 Offline");
*/
export declare function useOnlineStatus(): boolean;
/**
* useWindowSize Hook
*
* Tracks the current width and height of the browser window.
* Automatically updates on resize.
*
* @returns { width: number, height: number } - The current window dimensions.
*
* @example
* const { width, height } = useWindowSize();
* console.log(`Width: ${width}, Height: ${height}`);
*/
export declare function useWindowSize(): {
width: number;
height: number;
};
/**
* @file useAsync.ts
* @description A React hook for managing asynchronous operations with built-in
* loading, error, and result state handling.
*
* @example
* const { execute, data, error, isLoading } = useAsync(fetchUsers);
*
* useEffect(() => {
* execute();
* }, [execute]);
*/
export interface UseAsyncReturn<T, E = Error> {
/** Executes the async function manually */
execute: (...args: any[]) => Promise<T | undefined>;
/** The last successful result */
data: T | null;
/** Any error thrown by the async function */
error: E | null;
/** Indicates whether the async operation is in progress */
isLoading: boolean;
/** Resets data and error state */
reset: () => void;
}
/**
* A React hook for managing asynchronous operations.
*
* @param asyncFunction The async function to execute.
* @param immediate If true, runs immediately on mount.
*
* @returns An object containing data, error, loading, and helper methods.
*/
export declare function useAsync<T, E = Error>(asyncFunction: (...args: any[]) => Promise<T>, immediate?: boolean): UseAsyncReturn<T, E>;
export default useAsync;
/**
* @file useDebounce.ts
* @description A React hook that debounces a changing value over a given delay.
* Useful for performance optimization in search inputs, filters, or resize events.
*
* @example
* const [search, setSearch] = useState('');
* const debouncedSearch = useDebounce(search, 500);
*
* useEffect(() => {
* if (debouncedSearch) {
* fetchData(debouncedSearch);
* }
* }, [debouncedSearch]);
*/
/**
* Custom hook to debounce a value over a specified delay.
*
* @param value - The value to debounce.
* @param delay - The delay in milliseconds before updating the debounced value.
* @returns The debounced value that updates only after the specified delay.
*/
export declare function useDebounce<T>(value: T, delay?: number): T;
export default useDebounce;
/**
* useInterval Hook
*
* Runs a callback function at a specified interval, ensuring
* the latest version of the callback is always used.
*
* @param callback - Function to execute on each interval tick.
* @param delay - Time in milliseconds between each tick. Pass `null` to pause.
*
* @example
* useInterval(() => {
* console.log("Tick:", Date.now());
* }, 1000);
*/
export declare function useInterval(callback: () => void, delay: number | null): void;
/**
* @file useThrottle.ts
* @description A React hook that throttles a changing value over a given delay.
* Ensures the value updates at most once within the specified interval.
*
* @example
* const [scrollY, setScrollY] = useState(window.scrollY);
* const throttledScrollY = useThrottle(scrollY, 200);
*
* useEffect(() => {
* const onScroll = () => setScrollY(window.scrollY);
* window.addEventListener('scroll', onScroll);
* return () => window.removeEventListener('scroll', onScroll);
* }, []);
*
* useEffect(() => {
* console.log("Throttled scroll position:", throttledScrollY);
* }, [throttledScrollY]);
*/
/**
* Custom hook to throttle a value — updates only once per specified delay.
*
* @param value - The value to throttle.
* @param delay - The minimum time interval (in milliseconds) before updating again.
* @returns The throttled value that updates at most once per delay interval.
*/
export declare function useThrottle<T>(value: T, delay?: number): T;
export default useThrottle;
/**
* useTimeout Hook
*
* Executes a callback function after a specified delay.
* Automatically handles cleanup and allows for manual cancel/reset.
*
* @param callback - Function to execute after the delay
* @param delay - Delay in milliseconds (or null to disable)
*
* @returns {Object} - Control functions:
* - clear(): Cancels the timeout
* - reset(): Resets and restarts the timeout
*
* @example
* const { clear, reset } = useTimeout(() => console.log("Hello!"), 3000);
*/
export declare function useTimeout(callback: () => void, delay: number | null): {
clear: () => void;
reset: () => void;
};
import { EffectCallback, DependencyList } from 'react';
/**
* useUpdateEffect Hook
*
* Works like useEffect but skips execution on the first render.
*
* @param effect - The effect callback to run.
* @param deps - Dependency list that triggers the effect.
*
* @example
* useUpdateEffect(() => {
* console.log("Runs only when count changes, not on mount");
* }, [count]);
*/
export declare function useUpdateEffect(effect: EffectCallback, deps?: DependencyList): void;
/**
* @file useArray.ts
* @description A React hook for managing array state with convenient helper methods.
* Provides immutable operations such as push, remove, update, and clear.
*
* @example
* const { array, push, remove, update, clear } = useArray<number>([1, 2, 3]);
*
* push(4); // [1, 2, 3, 4]
* remove(1); // [1, 3, 4]
* update(0, 10); // [10, 3, 4]
* clear(); // []
*/
/**
* A hook to manage array state with built-in immutable operations.
*
* @param initialValue - The initial array value.
* @returns An object containing the array and helper functions.
*/
export declare function useArray<T>(initialValue?: T[]): {
array: T[];
set: (newArray: T[]) => void;
push: (element: T) => void;
remove: (index: number) => void;
update: (index: number, newElement: T) => void;
insert: (index: number, element: T) => void;
clear: () => void;
isEmpty: boolean;
};
export default useArray;
/**
* @file useBoolean.ts
* @description A React hook for managing boolean state with handy utilities to toggle, set true, and set false.
*
* @example
* const { value, setTrue, setFalse, toggle } = useBoolean(false);
*
* // Usage in a component:
* <button onClick={toggle}>Toggle</button>
* <button onClick={setTrue}>Enable</button>
* <button onClick={setFalse}>Disable</button>
*/
/**
* The return type of the useBoolean hook.
*/
export interface UseBooleanReturn {
/** The current boolean value */
value: boolean;
/** Sets the value to true */
setTrue: () => void;
/** Sets the value to false */
setFalse: () => void;
/** Toggles the current value */
toggle: () => void;
/** Manually sets a specific boolean value */
setValue: (newValue: boolean) => void;
}
/**
* A React hook for managing boolean state with convenient setter functions.
*
* @param initialValue The initial boolean state (default: false)
* @returns An object containing the current value and functions to modify it
*/
export declare function useBoolean(initialValue?: boolean): UseBooleanReturn;
export default useBoolean;
/**
* @file useCounter.ts
* @description A React hook for managing numeric state with increment, decrement, reset, and custom set capabilities.
*
* @example
* const { count, increment, decrement, reset, set } = useCounter(0, { min: 0, max: 10 });
*
* <button onClick={decrement}>-</button>
* <span>{count}</span>
* <button onClick={increment}>+</button>
*/
export interface UseCounterOptions {
/** Minimum value for the counter (optional) */
min?: number;
/** Maximum value for the counter (optional) */
max?: number;
/** Step value for increment/decrement (default: 1) */
step?: number;
}
export interface UseCounterReturn {
/** Current counter value */
count: number;
/** Increments the counter */
increment: () => void;
/** Decrements the counter */
decrement: () => void;
/** Resets the counter to the initial value */
reset: () => void;
/** Manually sets a specific value */
set: (value: number) => void;
}
/**
* A React hook to manage counter state with optional min, max, and step control.
*
* @param initialValue Initial counter value
* @param options Optional configuration for min, max, and step
* @returns An object with counter value and control methods
*/
export declare function useCounter(initialValue?: number, options?: UseCounterOptions): UseCounterReturn;
export default useCounter;
/**
* useFormState Hook
*
* A powerful hook to manage form data, validation, and submission.
*
* @template T - Type of the form data object
*
* @param initialValues - Initial form values
* @param validate - Optional validation function that returns errors
*
* @returns {{
* values: T;
* errors: Partial<Record<keyof T, string>>;
* touched: Partial<Record<keyof T, boolean>>;
* isSubmitting: boolean;
* handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
* handleBlur: (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
* handleSubmit: (onSubmit: (values: T) => void | Promise<void>) => (e: React.FormEvent) => void;
* resetForm: () => void;
* }}
*
* @example
* const { values, errors, handleChange, handleSubmit } = useFormState(
* { name: '', email: '' },
* (values) => {
* const errors: any = {};
* if (!values.name) errors.name = 'Name is required';
* if (!values.email.includes('@')) errors.email = 'Invalid email';
* return errors;
* }
* );
*
* return (
* <form onSubmit={handleSubmit((vals) => console.log(vals))}>
* <input name="name" value={values.name} onChange={handleChange} />
* {errors.name && <span>{errors.name}</span>}
*
* <input name="email" value={values.email} onChange={handleChange} />
* {errors.email && <span>{errors.email}</span>}
*
* <button type="submit">Submit</button>
* </form>
* );
*/
export declare function useFormState<T extends Record<string, any>>(initialValues: T, validate?: (values: T) => Partial<Record<keyof T, string>>): {
values: T;
errors: Partial<Record<keyof T, string>>;
touched: Partial<Record<keyof T, boolean>>;
isSubmitting: boolean;
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
handleBlur: (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
handleSubmit: (onSubmit: (values: T) => void | Promise<void>) => (e: React.FormEvent) => Promise<void>;
resetForm: () => void;
};
/**
* @file usePrevious.ts
* @description A React hook that stores the previous value of a state or prop.
* This is helpful for comparing current and past values between renders.
*
* @example
* const [count, setCount] = useState(0);
* const prevCount = usePrevious(count);
*
* useEffect(() => {
* if (prevCount !== undefined && prevCount !== count) {
* console.log(`Count changed from ${prevCount} → ${count}`);
* }
* }, [count, prevCount]);
*/
/**
* Custom hook to get the previous value of a variable.
*
* @param value - The current value you want to track.
* @returns The value from the previous render (or undefined on the first render).
*/
export declare function usePrevious<T>(value: T): T | undefined;
export default usePrevious;
/**
* useRefState Hook
*
* Combines useState and useRef to provide both reactive and synchronous access
* to the current state value.
*
* @param initialValue - The initial state value.
*
* @returns [state, setState, ref] - A tuple where:
* - `state` is the current value (reactive, causes re-renders)
* - `setState` updates the value (just like useState)
* - `ref` always points to the latest value (non-reactive)
*
* @example
* const [count, setCount, countRef] = useRefState(0);
*
* useEffect(() => {
* const interval = setInterval(() => {
* console.log("Current count:", countRef.current);
* }, 1000);
* return () => clearInterval(interval);
* }, []);
*/
export declare function useRefState<T>(initialValue: T): [T, (value: T | ((prev: T) => T)) => void, React.MutableRefObject<T>];
/**
* @file useToggle.ts
* @description A simple React hook to manage boolean toggle state.
* Useful for toggling visibility, modals, switches, etc.
*
* @example
* const [isOpen, toggleOpen] = useToggle(false);
*
* // To toggle value
* toggleOpen();
*
* // To explicitly set value
* toggleOpen(true);
*
* @returns [value, toggle]
* - value: current boolean state
* - toggle: function to toggle or set boolean value
*/
/**
* Custom hook for managing boolean state with toggle functionality.
*
* @param initialValue - The initial boolean value (default: false)
* @returns [value, toggle]
* - `value`: The current boolean state.
* - `toggle`: A function to toggle the state or set it explicitly.
*/
export declare function useToggle(initialValue?: boolean): [boolean, (nextValue?: boolean) => void];
export default useToggle;
/**
* A React hook that synchronizes state with localStorage.
*
* @template T - The data type of the stored value
* @param key - The localStorage key to read/write
* @param initialValue - The initial value used if localStorage is empty or invalid
* @returns A tuple [value, setValue, removeValue]
*
* @example
* const [user, setUser, removeUser] = useLocalStorage("user", { name: "John" });
*
* // Update
* setUser({ name: "Jane" });
*
* // Remove
* removeUser();
*/
export declare function useLocalStorage<T>(key: string, initialValue: T): readonly [T, (value: T | ((prev: T) => T)) => void, () => void];
/**
* useSessionStorage Hook
*
* Synchronizes state with `sessionStorage`.
* The data persists for the duration of the page session
* and is cleared when the tab or browser is closed.
*
* @param key - The key to store the value under in sessionStorage.
* @param initialValue - The default value used if nothing is stored.
*
* @returns [value, setValue] - Current stored value and a setter function.
*
* @example
* const [user, setUser] = useSessionStorage("user", null);
*/
export declare function useSessionStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void];
import { Meta, StoryObj } from '@storybook/react';
declare const meta: Meta;
export default meta;
type Story = StoryObj;
export declare const Default: Story;
import { default as React } from 'react';
import { Meta, StoryObj } from '@storybook/react';
declare const DemoAsyncComponent: React.FC;
declare const meta: Meta<typeof DemoAsyncComponent>;
export default meta;
type Story = StoryObj<typeof DemoAsyncComponent>;
export declare const Default: Story;
import { Meta, StoryObj } from '@storybook/react';
declare const BooleanDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof BooleanDemo>;
export default meta;
export declare const Default: StoryObj<typeof BooleanDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const ClickOutsideDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof ClickOutsideDemo>;
export default meta;
export declare const Default: StoryObj<typeof ClickOutsideDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const CopyToClipboardDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof CopyToClipboardDemo>;
export default meta;
export declare const Default: StoryObj<typeof CopyToClipboardDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const CounterDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof CounterDemo>;
export default meta;
export declare const Default: StoryObj<typeof CounterDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const DarkModeDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof DarkModeDemo>;
export default meta;
export declare const Default: StoryObj<typeof DarkModeDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const DebounceDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof DebounceDemo>;
export default meta;
export declare const Default: StoryObj<typeof DebounceDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const DeviceOrientationDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof DeviceOrientationDemo>;
export default meta;
export declare const Default: StoryObj<typeof DeviceOrientationDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const EventListenerDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof EventListenerDemo>;
export default meta;
export declare const Default: StoryObj<typeof EventListenerDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const FocusDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof FocusDemo>;
export default meta;
export declare const Default: StoryObj<typeof FocusDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const FormDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof FormDemo>;
export default meta;
export declare const Default: StoryObj<typeof FormDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const HoverDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof HoverDemo>;
export default meta;
export declare const Default: StoryObj<typeof HoverDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const InputDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof InputDemo>;
export default meta;
export declare const Default: StoryObj<typeof InputDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const IntervalDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof IntervalDemo>;
export default meta;
export declare const Default: StoryObj<typeof IntervalDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const LocalStorageDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof LocalStorageDemo>;
export default meta;
export declare const Default: StoryObj<typeof LocalStorageDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const MapDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof MapDemo>;
export default meta;
export declare const Default: StoryObj<typeof MapDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const OnlineStatusDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof OnlineStatusDemo>;
export default meta;
export declare const Default: StoryObj<typeof OnlineStatusDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const PreviousDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof PreviousDemo>;
export default meta;
export declare const Default: StoryObj<typeof PreviousDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const RafStateDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof RafStateDemo>;
export default meta;
export declare const Default: StoryObj<typeof RafStateDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const SessionStorageDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof SessionStorageDemo>;
export default meta;
export declare const Default: StoryObj<typeof SessionStorageDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const ThrottleDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof ThrottleDemo>;
export default meta;
export declare const Default: StoryObj<typeof ThrottleDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const TimeoutDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof TimeoutDemo>;
export default meta;
export declare const Default: StoryObj<typeof TimeoutDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const ToggleDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof ToggleDemo>;
export default meta;
export declare const Default: StoryObj<typeof ToggleDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const UpdateEffectDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof UpdateEffectDemo>;
export default meta;
export declare const Default: StoryObj<typeof UpdateEffectDemo>;
import { Meta, StoryObj } from '@storybook/react';
declare const WindowSizeDemo: () => import("react/jsx-runtime").JSX.Element;
declare const meta: Meta<typeof WindowSizeDemo>;
export default meta;
export declare const Default: StoryObj<typeof WindowSizeDemo>;
/**
* @file useClickOutside.ts
* @description A React hook that detects and handles clicks outside of a referenced element.
*
* @example
* const ref = useRef(null);
* useClickOutside(ref, () => setOpen(false));
*
* return <div ref={ref}>Dropdown Content</div>;
*/
/**
* A React hook to detect clicks outside a given element.
*
* @param ref - React ref object for the target element.
* @param handler - Callback function invoked when a click occurs outside the element.
* @param eventType - The event type to listen for (default: 'mousedown').
*/
export declare function useClickOutside<T extends HTMLElement | null = HTMLElement>(ref: React.RefObject<T>, handler: (event: MouseEvent | TouchEvent) => void, eventType?: "mousedown" | "mouseup" | "click" | "touchstart"): void;
export default useClickOutside;
/**
* @file useDarkMode.ts
* @description A React hook for managing and persisting dark mode preference.
*
* @example
* const { isDarkMode, toggle, enable, disable } = useDarkMode();
*
* <button onClick={toggle}>
* {isDarkMode ? "Switch to Light Mode" : "Switch to Dark Mode"}
* </button>
*/
export interface UseDarkModeReturn {
/** Whether dark mode is currently active */
isDarkMode: boolean;
/** Enables dark mode */
enable: () => void;
/** Disables dark mode */
disable: () => void;
/** Toggles dark mode */
toggle: () => void;
}
/**
* A React hook that manages dark mode with persistence and system preference detection.
*
* @param storageKey - Key used for storing the theme preference in localStorage.
* @param defaultValue - Optional default value if no preference is found.
* @returns An object with `isDarkMode`, `enable`, `disable`, and `toggle`.
*/
export declare function useDarkMode(storageKey?: string, defaultValue?: boolean): UseDarkModeReturn;
export default useDarkMode;
interface DeviceOrientation {
alpha: number | null;
beta: number | null;
gamma: number | null;
absolute: boolean | null;
}
/**
* useDeviceOrientation Hook
* Tracks the physical orientation of the device (alpha, beta, gamma)
* using the DeviceOrientationEvent API.
*
* @returns {DeviceOrientation} Current orientation angles and absolute flag
*
* @example
* const { alpha, beta, gamma, absolute } = useDeviceOrientation();
* console.log(alpha, beta, gamma);
*/
export declare function useDeviceOrientation(): DeviceOrientation;
export {};
/**
* useFocus Hook
* Provides an easy way to manage focus state on a DOM element.
*
* @returns {{
* ref: React.RefObject<HTMLElement>;
* focus: () => void;
* blur: () => void;
* isFocused: boolean;
* }}
*
* @example
* const { ref, focus, blur, isFocused } = useFocus();
*
* return (
* <div>
* <input ref={ref} placeholder="Focus me" />
* <button onClick={focus}>Focus</button>
* <button onClick={blur}>Blur</button>
* <p>{isFocused ? "Focused" : "Not Focused"}</p>
* </div>
* );
*/
export declare function useFocus<T extends HTMLElement>(): {
ref: import('react').RefObject<T | null>;
focus: () => void;
blur: () => void;
isFocused: boolean;
};
/**
* useHover Hook
*
* Tracks whether a referenced DOM element is currently hovered by the user.
*
* @returns {{
* ref: React.RefObject<T>;
* isHovered: boolean;
* }}
*
* @example
* const { ref, isHovered } = useHover<HTMLDivElement>();
*
* return (
* <div ref={ref} style={{ background: isHovered ? 'lightblue' : 'white' }}>
* Hover over me!
* </div>
* );
*/
export declare function useHover<T extends HTMLElement>(): {
ref: import('react').RefObject<T | null>;
isHovered: boolean;
};
/**
* useMediaQuery Hook
*
* React hook that listens to a CSS media query and returns whether it matches.
*
* @param query - A valid CSS media query string (e.g. "(max-width: 768px)")
*
* @returns boolean - true if the query matches, false otherwise
*
* @example
* const isMobile = useMediaQuery("(max-width: 768px)");
* const prefersDark = useMediaQuery("(prefers-color-scheme: dark)");
*/
export declare function useMediaQuery(query: string): boolean;
+28
-28

@@ -1,28 +0,28 @@

export * from './hooks/useToggle';
export * from './hooks/useArray';
export * from './hooks/useLocalStorage';
export * from './hooks/useDebounce';
export * from './hooks/usePrevious';
export * from './hooks/useClickOutside';
export * from './hooks/useEventListener';
export * from './hooks/useDarkMode';
export * from './hooks/useCopyToClipboard';
export * from './hooks/useMediaQuery';
export * from './hooks/useHover';
export * from './hooks/useWindowSize';
export * from './hooks/useAsync';
export * from './hooks/useBoolean';
export * from './hooks/useCounter';
export * from './hooks/useDeviceOrientation';
export * from './hooks/useFocus';
export * from './hooks/useFormState';
export * from './hooks/useInput';
export * from './hooks/useInterval';
export * from './hooks/useLocalStorage';
export * from './hooks/useMap';
export * from './hooks/useOnlineStatus';
export * from './hooks/useRafState';
export * from './hooks/useSessionStorage';
export * from './hooks/useThrottle';
export * from './hooks/useTimeout';
export * from './hooks/useUpdateEffect';
export * from './hooks/state/useToggle';
export * from './hooks/state/useArray';
export * from './hooks/storage/useLocalStorage';
export * from './hooks/effects/useDebounce';
export * from './hooks/state/usePrevious';
export * from './hooks/ui/useClickOutside';
export * from './hooks/browser/useEventListener';
export * from './hooks/ui/useDarkMode';
export * from './hooks/browser/useCopyToClipboard';
export * from './hooks/ui/useMediaQuery';
export * from './hooks/ui/useHover';
export * from './hooks/browser/useWindowSize';
export * from './hooks/effects/useAsync';
export * from './hooks/state/useBoolean';
export * from './hooks/state/useCounter';
export * from './hooks/ui/useDeviceOrientation';
export * from './hooks/ui/useFocus';
export * from './hooks/state/useFormState';
export * from './hooks/browser/useInput';
export * from './hooks/effects/useInterval';
export * from './hooks/storage/useLocalStorage';
export * from './hooks/browser/useMap';
export * from './hooks/browser/useOnlineStatus';
export * from './hooks/state/useRafState';
export * from './hooks/storage/useSessionStorage';
export * from './hooks/effects/useThrottle';
export * from './hooks/effects/useTimeout';
export * from './hooks/effects/useUpdateEffect';
{
"name": "react-hookstack",
"version": "1.0.4",
"version": "1.0.5",
"description": "A collection of powerful and reusable React hooks.",

@@ -15,5 +15,10 @@ "main": "dist/react-handyhooks.umd.js",

"preview": "vite preview",
"test": "jest"
"test": "jest",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/material": "^7.3.4",
"react": ">=18",

@@ -24,2 +29,4 @@ "react-dom": ">=18"

"@eslint/js": "^9.36.0",
"@storybook/addon-docs": "^9.1.13",
"@storybook/react-vite": "^9.1.13",
"@testing-library/jest-dom": "^6.9.1",

@@ -29,3 +36,3 @@ "@testing-library/react": "^16.3.0",

"@types/node": "^24.6.0",
"@types/react": "^19.1.16",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.1.9",

@@ -36,2 +43,3 @@ "@vitejs/plugin-react": "^5.0.4",

"eslint-plugin-react-refresh": "^0.4.22",
"eslint-plugin-storybook": "^9.1.13",
"globals": "^16.4.0",

@@ -41,3 +49,5 @@ "jest": "^30.2.0",

"markdown-include": "^0.4.3",
"storybook": "^9.1.13",
"ts-jest": "^29.4.5",
"tslib": "^2.8.1",
"typescript": "~5.9.3",

@@ -44,0 +54,0 @@ "typescript-eslint": "^8.45.0",

# ⚡ React Hookstack
[![build](https://img.shields.io/github/actions/workflow/status/Shakir-Afridi/react-handyhooks/.github/workflows/public.yml?branch=dev)](https://github.com/Shakir-Afridi/react-handyhooks/actions)
[![license](https://img.shields.io/github/license/Shakir-Afridi/react-handyhooks)](LICENSE)

@@ -23,2 +24,7 @@ [![issues](https://img.shields.io/github/issues/Shakir-Afridi/react-handyhooks)](https://github.com/Shakir-Afridi/react-handyhooks/issues)

## 📘 Storybook
Explore all hooks interactively on Storybook:
👉 [Live Demo](https://shakir-afridi.github.io/react-handyhooks/)
## 📦 Installation

@@ -25,0 +31,0 @@

/**
* @file useArray.ts
* @description A React hook for managing array state with convenient helper methods.
* Provides immutable operations such as push, remove, update, and clear.
*
* @example
* const { array, push, remove, update, clear } = useArray<number>([1, 2, 3]);
*
* push(4); // [1, 2, 3, 4]
* remove(1); // [1, 3, 4]
* update(0, 10); // [10, 3, 4]
* clear(); // []
*/
/**
* A hook to manage array state with built-in immutable operations.
*
* @param initialValue - The initial array value.
* @returns An object containing the array and helper functions.
*/
export declare function useArray<T>(initialValue?: T[]): {
array: T[];
set: (newArray: T[]) => void;
push: (element: T) => void;
remove: (index: number) => void;
update: (index: number, newElement: T) => void;
insert: (index: number, element: T) => void;
clear: () => void;
isEmpty: boolean;
};
export default useArray;
/**
* @file useAsync.ts
* @description A React hook for managing asynchronous operations with built-in
* loading, error, and result state handling.
*
* @example
* const { execute, data, error, isLoading } = useAsync(fetchUsers);
*
* useEffect(() => {
* execute();
* }, [execute]);
*/
export interface UseAsyncReturn<T, E = Error> {
/** Executes the async function manually */
execute: (...args: any[]) => Promise<T | undefined>;
/** The last successful result */
data: T | null;
/** Any error thrown by the async function */
error: E | null;
/** Indicates whether the async operation is in progress */
isLoading: boolean;
/** Resets data and error state */
reset: () => void;
}
/**
* A React hook for managing asynchronous operations.
*
* @param asyncFunction The async function to execute.
* @param immediate If true, runs immediately on mount.
*
* @returns An object containing data, error, loading, and helper methods.
*/
export declare function useAsync<T, E = Error>(asyncFunction: (...args: any[]) => Promise<T>, immediate?: boolean): UseAsyncReturn<T, E>;
export default useAsync;
/**
* @file useBoolean.ts
* @description A React hook for managing boolean state with handy utilities to toggle, set true, and set false.
*
* @example
* const { value, setTrue, setFalse, toggle } = useBoolean(false);
*
* // Usage in a component:
* <button onClick={toggle}>Toggle</button>
* <button onClick={setTrue}>Enable</button>
* <button onClick={setFalse}>Disable</button>
*/
/**
* The return type of the useBoolean hook.
*/
export interface UseBooleanReturn {
/** The current boolean value */
value: boolean;
/** Sets the value to true */
setTrue: () => void;
/** Sets the value to false */
setFalse: () => void;
/** Toggles the current value */
toggle: () => void;
/** Manually sets a specific boolean value */
setValue: (newValue: boolean) => void;
}
/**
* A React hook for managing boolean state with convenient setter functions.
*
* @param initialValue The initial boolean state (default: false)
* @returns An object containing the current value and functions to modify it
*/
export declare function useBoolean(initialValue?: boolean): UseBooleanReturn;
export default useBoolean;
/**
* @file useClickOutside.ts
* @description A React hook that detects and handles clicks outside of a referenced element.
*
* @example
* const ref = useRef(null);
* useClickOutside(ref, () => setOpen(false));
*
* return <div ref={ref}>Dropdown Content</div>;
*/
/**
* A React hook to detect clicks outside a given element.
*
* @param ref - React ref object for the target element.
* @param handler - Callback function invoked when a click occurs outside the element.
* @param eventType - The event type to listen for (default: 'mousedown').
*/
export declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: React.RefObject<T>, handler: (event: MouseEvent | TouchEvent) => void, eventType?: "mousedown" | "mouseup" | "click" | "touchstart"): void;
export default useClickOutside;
/**
* @file useCopyToClipboard.ts
* @description A React hook to copy text to the clipboard with success feedback.
*
* @example
* const { copy, value, success } = useCopyToClipboard();
*
* <button onClick={() => copy("Hello World!")}>
* {success ? "Copied!" : "Copy Text"}
* </button>
*/
export interface UseCopyToClipboardReturn {
/** The last copied value */
value: string | null;
/** Whether the last copy attempt was successful */
success: boolean;
/** Copies the given text to the clipboard */
copy: (text: string) => Promise<boolean>;
/** Resets the state */
reset: () => void;
}
/**
* A hook that provides clipboard copy functionality.
*
* It supports both the modern Clipboard API and falls back to
* `document.execCommand` for older browsers.
*
* @returns An object with `copy`, `value`, `success`, and `reset`.
*/
export declare function useCopyToClipboard(): UseCopyToClipboardReturn;
export default useCopyToClipboard;
/**
* @file useCounter.ts
* @description A React hook for managing numeric state with increment, decrement, reset, and custom set capabilities.
*
* @example
* const { count, increment, decrement, reset, set } = useCounter(0, { min: 0, max: 10 });
*
* <button onClick={decrement}>-</button>
* <span>{count}</span>
* <button onClick={increment}>+</button>
*/
export interface UseCounterOptions {
/** Minimum value for the counter (optional) */
min?: number;
/** Maximum value for the counter (optional) */
max?: number;
/** Step value for increment/decrement (default: 1) */
step?: number;
}
export interface UseCounterReturn {
/** Current counter value */
count: number;
/** Increments the counter */
increment: () => void;
/** Decrements the counter */
decrement: () => void;
/** Resets the counter to the initial value */
reset: () => void;
/** Manually sets a specific value */
set: (value: number) => void;
}
/**
* A React hook to manage counter state with optional min, max, and step control.
*
* @param initialValue Initial counter value
* @param options Optional configuration for min, max, and step
* @returns An object with counter value and control methods
*/
export declare function useCounter(initialValue?: number, options?: UseCounterOptions): UseCounterReturn;
export default useCounter;
/**
* @file useDarkMode.ts
* @description A React hook for managing and persisting dark mode preference.
*
* @example
* const { isDarkMode, toggle, enable, disable } = useDarkMode();
*
* <button onClick={toggle}>
* {isDarkMode ? "Switch to Light Mode" : "Switch to Dark Mode"}
* </button>
*/
export interface UseDarkModeReturn {
/** Whether dark mode is currently active */
isDarkMode: boolean;
/** Enables dark mode */
enable: () => void;
/** Disables dark mode */
disable: () => void;
/** Toggles dark mode */
toggle: () => void;
}
/**
* A React hook that manages dark mode with persistence and system preference detection.
*
* @param storageKey - Key used for storing the theme preference in localStorage.
* @param defaultValue - Optional default value if no preference is found.
* @returns An object with `isDarkMode`, `enable`, `disable`, and `toggle`.
*/
export declare function useDarkMode(storageKey?: string, defaultValue?: boolean): UseDarkModeReturn;
export default useDarkMode;
/**
* @file useDebounce.ts
* @description A React hook that debounces a changing value over a given delay.
* Useful for performance optimization in search inputs, filters, or resize events.
*
* @example
* const [search, setSearch] = useState('');
* const debouncedSearch = useDebounce(search, 500);
*
* useEffect(() => {
* if (debouncedSearch) {
* fetchData(debouncedSearch);
* }
* }, [debouncedSearch]);
*/
/**
* Custom hook to debounce a value over a specified delay.
*
* @param value - The value to debounce.
* @param delay - The delay in milliseconds before updating the debounced value.
* @returns The debounced value that updates only after the specified delay.
*/
export declare function useDebounce<T>(value: T, delay?: number): T;
export default useDebounce;
interface DeviceOrientation {
alpha: number | null;
beta: number | null;
gamma: number | null;
absolute: boolean | null;
}
/**
* useDeviceOrientation Hook
* Tracks the physical orientation of the device (alpha, beta, gamma)
* using the DeviceOrientationEvent API.
*
* @returns {DeviceOrientation} Current orientation angles and absolute flag
*
* @example
* const { alpha, beta, gamma, absolute } = useDeviceOrientation();
* console.log(alpha, beta, gamma);
*/
export declare function useDeviceOrientation(): DeviceOrientation;
export {};
/**
* @file useEventListener.ts
* @description A React hook for safely adding and cleaning up event listeners.
* Works for both window, document, or specific DOM elements.
*
* @example
* // Example: Listening to window resize
* useEventListener('resize', () => console.log('Window resized!'));
*
* // Example: Listening to key press
* useEventListener('keydown', (e) => {
* if (e.key === 'Escape') console.log('Escape pressed!');
* });
*/
/**
* Custom hook to attach an event listener to a target element (window by default).
*
* @param eventName - The name of the event to listen for (e.g., 'click', 'resize').
* @param handler - The event handler function.
* @param element - Optional target element (defaults to window).
*/
export declare function useEventListener<K extends keyof WindowEventMap>(eventName: K, handler: (event: WindowEventMap[K]) => void, element?: Window | Document | HTMLElement | null): void;
export default useEventListener;
/**
* useFocus Hook
* Provides an easy way to manage focus state on a DOM element.
*
* @returns {{
* ref: React.RefObject<HTMLElement>;
* focus: () => void;
* blur: () => void;
* isFocused: boolean;
* }}
*
* @example
* const { ref, focus, blur, isFocused } = useFocus();
*
* return (
* <div>
* <input ref={ref} placeholder="Focus me" />
* <button onClick={focus}>Focus</button>
* <button onClick={blur}>Blur</button>
* <p>{isFocused ? "Focused" : "Not Focused"}</p>
* </div>
* );
*/
export declare function useFocus<T extends HTMLElement>(): {
ref: import('react').RefObject<T | null>;
focus: () => void;
blur: () => void;
isFocused: boolean;
};
/**
* useFormState Hook
*
* A powerful hook to manage form data, validation, and submission.
*
* @template T - Type of the form data object
*
* @param initialValues - Initial form values
* @param validate - Optional validation function that returns errors
*
* @returns {{
* values: T;
* errors: Partial<Record<keyof T, string>>;
* touched: Partial<Record<keyof T, boolean>>;
* isSubmitting: boolean;
* handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
* handleBlur: (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
* handleSubmit: (onSubmit: (values: T) => void | Promise<void>) => (e: React.FormEvent) => void;
* resetForm: () => void;
* }}
*
* @example
* const { values, errors, handleChange, handleSubmit } = useFormState(
* { name: '', email: '' },
* (values) => {
* const errors: any = {};
* if (!values.name) errors.name = 'Name is required';
* if (!values.email.includes('@')) errors.email = 'Invalid email';
* return errors;
* }
* );
*
* return (
* <form onSubmit={handleSubmit((vals) => console.log(vals))}>
* <input name="name" value={values.name} onChange={handleChange} />
* {errors.name && <span>{errors.name}</span>}
*
* <input name="email" value={values.email} onChange={handleChange} />
* {errors.email && <span>{errors.email}</span>}
*
* <button type="submit">Submit</button>
* </form>
* );
*/
export declare function useFormState<T extends Record<string, any>>(initialValues: T, validate?: (values: T) => Partial<Record<keyof T, string>>): {
values: T;
errors: Partial<Record<keyof T, string>>;
touched: Partial<Record<keyof T, boolean>>;
isSubmitting: boolean;
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
handleBlur: (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
handleSubmit: (onSubmit: (values: T) => void | Promise<void>) => (e: React.FormEvent) => Promise<void>;
resetForm: () => void;
};
/**
* useHover Hook
*
* Tracks whether a referenced DOM element is currently hovered by the user.
*
* @returns {{
* ref: React.RefObject<T>;
* isHovered: boolean;
* }}
*
* @example
* const { ref, isHovered } = useHover<HTMLDivElement>();
*
* return (
* <div ref={ref} style={{ background: isHovered ? 'lightblue' : 'white' }}>
* Hover over me!
* </div>
* );
*/
export declare function useHover<T extends HTMLElement>(): {
ref: import('react').RefObject<T | null>;
isHovered: boolean;
};
/**
* useInput Hook
*
* Manages input value, validation, and change events.
*
* @param {string} initialValue - The initial value of the input field.
* @param {(value: string) => string | undefined} [validate] - Optional validation function that returns an error message.
*
* @returns {{
* value: string;
* error?: string;
* onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
* reset: () => void;
* setValue: React.Dispatch<React.SetStateAction<string>>;
* }}
*
* @example
* const name = useInput('', (val) => !val ? 'Name is required' : undefined);
*
* return (
* <div>
* <input {...name} placeholder="Enter your name" />
* {name.error && <span style={{ color: 'red' }}>{name.error}</span>}
* <button onClick={name.reset}>Reset</button>
* </div>
* );
*/
export declare function useInput(initialValue?: string, validate?: (value: string) => string | undefined): {
value: string;
error: string | undefined;
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
reset: () => void;
setValue: import('react').Dispatch<import('react').SetStateAction<string>>;
};
/**
* useInterval Hook
*
* Runs a callback function at a specified interval, ensuring
* the latest version of the callback is always used.
*
* @param callback - Function to execute on each interval tick.
* @param delay - Time in milliseconds between each tick. Pass `null` to pause.
*
* @example
* useInterval(() => {
* console.log("Tick:", Date.now());
* }, 1000);
*/
export declare function useInterval(callback: () => void, delay: number | null): void;
/**
* A React hook that synchronizes state with localStorage.
*
* @template T - The data type of the stored value
* @param key - The localStorage key to read/write
* @param initialValue - The initial value used if localStorage is empty or invalid
* @returns A tuple [value, setValue, removeValue]
*
* @example
* const [user, setUser, removeUser] = useLocalStorage("user", { name: "John" });
*
* // Update
* setUser({ name: "Jane" });
*
* // Remove
* removeUser();
*/
export declare function useLocalStorage<T>(key: string, initialValue: T): readonly [T, (value: T | ((prev: T) => T)) => void, () => void];
/**
* useMap Hook
*
* A React hook to manage a Map with helpful utility functions.
*
* @template K - Key type
* @template V - Value type
*
* @param initialEntries - Optional initial entries for the Map
*
* @returns {{
* map: Map<K, V>;
* set: (key: K, value: V) => void;
* get: (key: K) => V | undefined;
* remove: (key: K) => void;
* has: (key: K) => boolean;
* clear: () => void;
* reset: () => void;
* }}
*
* @example
* const { map, set, get, remove, clear } = useMap<string, number>([['a', 1]]);
*
* set('b', 2);
* console.log(map.get('a')); // 1
* remove('a');
* clear();
*/
export declare function useMap<K, V>(initialEntries?: readonly (readonly [K, V])[]): {
map: Map<K, V>;
set: (key: K, value: V) => void;
get: (key: K) => V | undefined;
remove: (key: K) => void;
has: (key: K) => boolean;
clear: () => void;
reset: () => void;
};
/**
* useMediaQuery Hook
*
* React hook that listens to a CSS media query and returns whether it matches.
*
* @param query - A valid CSS media query string (e.g. "(max-width: 768px)")
*
* @returns boolean - true if the query matches, false otherwise
*
* @example
* const isMobile = useMediaQuery("(max-width: 768px)");
* const prefersDark = useMediaQuery("(prefers-color-scheme: dark)");
*/
export declare function useMediaQuery(query: string): boolean;
/**
* useOnlineStatus Hook
*
* Detects the user's current online/offline status and updates reactively.
*
* @returns boolean - true if the user is online, false if offline
*
* @example
* const isOnline = useOnlineStatus();
* console.log(isOnline ? "🟢 Online" : "🔴 Offline");
*/
export declare function useOnlineStatus(): boolean;
/**
* @file usePrevious.ts
* @description A React hook that stores the previous value of a state or prop.
* This is helpful for comparing current and past values between renders.
*
* @example
* const [count, setCount] = useState(0);
* const prevCount = usePrevious(count);
*
* useEffect(() => {
* if (prevCount !== undefined && prevCount !== count) {
* console.log(`Count changed from ${prevCount} → ${count}`);
* }
* }, [count, prevCount]);
*/
/**
* Custom hook to get the previous value of a variable.
*
* @param value - The current value you want to track.
* @returns The value from the previous render (or undefined on the first render).
*/
export declare function usePrevious<T>(value: T): T | undefined;
export default usePrevious;
/**
* useRefState Hook
*
* Combines useState and useRef to provide both reactive and synchronous access
* to the current state value.
*
* @param initialValue - The initial state value.
*
* @returns [state, setState, ref] - A tuple where:
* - `state` is the current value (reactive, causes re-renders)
* - `setState` updates the value (just like useState)
* - `ref` always points to the latest value (non-reactive)
*
* @example
* const [count, setCount, countRef] = useRefState(0);
*
* useEffect(() => {
* const interval = setInterval(() => {
* console.log("Current count:", countRef.current);
* }, 1000);
* return () => clearInterval(interval);
* }, []);
*/
export declare function useRefState<T>(initialValue: T): [T, (value: T | ((prev: T) => T)) => void, React.MutableRefObject<T>];
/**
* useSessionStorage Hook
*
* Synchronizes state with `sessionStorage`.
* The data persists for the duration of the page session
* and is cleared when the tab or browser is closed.
*
* @param key - The key to store the value under in sessionStorage.
* @param initialValue - The default value used if nothing is stored.
*
* @returns [value, setValue] - Current stored value and a setter function.
*
* @example
* const [user, setUser] = useSessionStorage("user", null);
*/
export declare function useSessionStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void];
/**
* @file useThrottle.ts
* @description A React hook that throttles a changing value over a given delay.
* Ensures the value updates at most once within the specified interval.
*
* @example
* const [scrollY, setScrollY] = useState(window.scrollY);
* const throttledScrollY = useThrottle(scrollY, 200);
*
* useEffect(() => {
* const onScroll = () => setScrollY(window.scrollY);
* window.addEventListener('scroll', onScroll);
* return () => window.removeEventListener('scroll', onScroll);
* }, []);
*
* useEffect(() => {
* console.log("Throttled scroll position:", throttledScrollY);
* }, [throttledScrollY]);
*/
/**
* Custom hook to throttle a value — updates only once per specified delay.
*
* @param value - The value to throttle.
* @param delay - The minimum time interval (in milliseconds) before updating again.
* @returns The throttled value that updates at most once per delay interval.
*/
export declare function useThrottle<T>(value: T, delay?: number): T;
export default useThrottle;
/**
* useTimeout Hook
*
* Executes a callback function after a specified delay.
* Automatically handles cleanup and allows for manual cancel/reset.
*
* @param callback - Function to execute after the delay
* @param delay - Delay in milliseconds (or null to disable)
*
* @returns {Object} - Control functions:
* - clear(): Cancels the timeout
* - reset(): Resets and restarts the timeout
*
* @example
* const { clear, reset } = useTimeout(() => console.log("Hello!"), 3000);
*/
export declare function useTimeout(callback: () => void, delay: number | null): {
clear: () => void;
reset: () => void;
};
/**
* @file useToggle.ts
* @description A simple React hook to manage boolean toggle state.
* Useful for toggling visibility, modals, switches, etc.
*
* @example
* const [isOpen, toggleOpen] = useToggle(false);
*
* // To toggle value
* toggleOpen();
*
* // To explicitly set value
* toggleOpen(true);
*
* @returns [value, toggle]
* - value: current boolean state
* - toggle: function to toggle or set boolean value
*/
/**
* Custom hook for managing boolean state with toggle functionality.
*
* @param initialValue - The initial boolean value (default: false)
* @returns [value, toggle]
* - `value`: The current boolean state.
* - `toggle`: A function to toggle the state or set it explicitly.
*/
export declare function useToggle(initialValue?: boolean): [boolean, (nextValue?: boolean) => void];
export default useToggle;
import { EffectCallback, DependencyList } from 'react';
/**
* useUpdateEffect Hook
*
* Works like useEffect but skips execution on the first render.
*
* @param effect - The effect callback to run.
* @param deps - Dependency list that triggers the effect.
*
* @example
* useUpdateEffect(() => {
* console.log("Runs only when count changes, not on mount");
* }, [count]);
*/
export declare function useUpdateEffect(effect: EffectCallback, deps?: DependencyList): void;
/**
* useWindowSize Hook
*
* Tracks the current width and height of the browser window.
* Automatically updates on resize.
*
* @returns { width: number, height: number } - The current window dimensions.
*
* @example
* const { width, height } = useWindowSize();
* console.log(`Width: ${width}, Height: ${height}`);
*/
export declare function useWindowSize(): {
width: number;
height: number;
};