rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
1,248 lines (1,169 loc) • 46.3 kB
TypeScript
import React, { DependencyList, MutableRefObject, Ref, Dispatch, SetStateAction, LegacyRef, AriaAttributes, DOMAttributes as DOMAttributes$1, AriaRole, CSSProperties, FocusEvent, RefCallback, ChangeEvent, useEffect, RefObject, Reducer, ReducerWithoutAction, DispatchWithoutAction } from 'react';
import { DebounceSettings, DebouncedFunc } from 'lodash';
declare type Push<T> = (...args: Parameters<Array<T>["push"]>) => void;
declare type Pop = () => void;
declare type Unshift<T> = (...args: Parameters<Array<T>["unshift"]>) => void;
declare type Shift = () => void;
declare type Reverse = () => void;
declare type Concat<T> = (value: T[]) => void;
declare type Fill<T> = (value: T, start?: number, end?: number) => void;
declare type Clear = () => void;
declare type UseArrayStateControls<T> = {
push: Push<T>;
pop: Pop;
clear: Clear;
unshift: Unshift<T>;
shift: Shift;
reverse: Reverse;
concat: Concat<T>;
fill: Fill<T>;
};
declare type UseArrayStateReturnValue<T> = [T[], UseArrayStateControls<T>];
/**
* useArrayState
* @description Array state manager hook for React
* @param {Array<T>} initialState Initial state of the array
* @returns {UseArrayStateReturnValue<T>} Array state manager hook for React
* @see {@link https://react-hooks.org/docs/useArrayState}
*
* @example
*
* const [array, controls] = useArrayState([1, 2, 3]);
*
* controls.push(4); // [1, 2, 3, 4]
* controls.pop(); // [1, 2, 3]
* controls.unshift(0); // [0, 1, 2, 3]
* controls.shift(); // [1, 2, 3]
* controls.reverse(); // [3, 2, 1]
* controls.concat([4, 5, 6]); // [3, 2, 1, 4, 5, 6]
* controls.fill(0); // [0, 0, 0, 0, 0, 0]
*/
declare function useArrayState<T>(initialArray?: T[]): UseArrayStateReturnValue<T>;
declare type Effect<T> = (shouldContinueEffect: () => boolean) => Promise<T>;
declare type CleanupFunction<T> = (result: T | void) => void;
/**
* A version of useEffect that accepts an async function
*
* @param {Effect<T>} effect Async function that can return a cleanup function and takes in an AbortSignal
* @param {DependencyList} deps If present, effect will only activate if the values in the list change
* @param {CleanupFunction} cleanup The destroy/cleanup function. Will be called with previous result if it exists.
* @see https://react-hooks.org/docs/useAsyncEffect
* @example
* ```jsx
* useAsyncEffect(
async (shouldContinueEffect) => {
const data1 = await fetchData1(arg1, arg2);
if(shouldContinueEffect()) {
const data2 = await fetchData2(arg1, arg2);
}
...
},
[arg1, arg2],
(previousResult) => {
// ... do something with previousResult ...
}
);
* ```
*/
declare function useAsyncEffect<T>(effect: Effect<T>, deps: DependencyList, cleanup?: CleanupFunction<T>): void;
//# sourceMappingURL=useAsyncEffect.d.ts.map
/**
* useBoundingclientRect hook
*
* @param ref The React ref whose ClientRect is needed
* @returns DOMRect | null
* @see https://react-hooks.org/docs/useBoundingclientRect
*/
declare function useBoundingclientrect(ref: MutableRefObject<HTMLElement | null>): DOMRect | null;
//# sourceMappingURL=useBoundingclientrect.d.ts.map
declare type HTMLElementOrNull = HTMLElement | null;
declare type RefElementOrNull<T> = T | null;
declare type CallbackRef<T extends HTMLElement | null = HTMLElementOrNull> = (node: T) => void;
declare type PossibleRef<T> = Ref<T> | undefined;
/**
* useBoundingclientrectRef hook
* Tracks the boundingclientrect of a React Ref and fires a callback when the element's size changes.
*
* @returns [CallbackRef | null, DOMRect | null, () => void]
* @see https://react-hooks.org/docs/useBoundingclientRectRef
*/
declare function useBoundingclientrectRef(): [
CallbackRef | null,
DOMRect | null,
() => void
];
//# sourceMappingURL=useBoundingclientrectRef.d.ts.map
declare type CountdownOptions = {
interval?: number;
onDown?: (restTime: number, newTime: Date) => void;
onEnd?: (newTime: Date) => void;
};
/**
*
* useCountdown
* Easy way to countdown until a given endtime in intervals
*
* @param endTime Time to countdown
* @param options Countdown options
* @see https://react-hooks.org/docs/useCountdown
*/
declare function useCountdown(endTime: Date, options?: CountdownOptions): number;
//# sourceMappingURL=useCountdown.d.ts.map
declare type CounterHandler = {
decrement: () => void;
decrementBy: (amount: number) => void;
increment: () => void;
incrementBy: (amount: number) => void;
reset: () => void;
value: number;
};
/**
*
* @typedef handler
* @type {object}
* @property {number} value The value of the counter
* @property {Function} increment Increment counter value by 1
* @property {Function} decrement Decrement counter value by 1
* @property {Function} incrementBy Increment counter by incrAmount
* @property {Function} decrementBy Decrement counter by decrAmount
* @property {Function} reset Reset counter to initialValue
* @see {@link https://react-hooks.org/docs/useCounter}
*/
/**
* Counter hook
*
* @param {number} initialValue The initial value of the counter
* @returns {handler} A handler to interact with the counter
* @see https://react-hooks.org/docs/useCounter
*/
declare function useCounter(initialValue: number): CounterHandler;
//# sourceMappingURL=useCounter.d.ts.map
declare type DeepNullable<T> = {
[K in keyof T]: DeepNullable<T[K]> | null;
};
declare type ListenerOptions = boolean | {
capture?: boolean;
once?: boolean;
passive?: boolean;
signal?: AbortSignal;
};
declare type UnknownFunction = (...args: unknown[]) => unknown;
declare type ExcludeFunction<T> = Exclude<T, UnknownFunction>;
/**
* Debounce hook
* Debounces a function
*
* @param callback The callback to debounce
* @param wait The duration to debounce
* @param options The options object.
* @param options.leading Specify invoking on the leading edge of the timeout.
* @param options.maxWait The maximum time func is allowed to be delayed before it’s invoked.
* @param options.trailing Specify invoking on the trailing edge of the timeout.
* @returns Returns the new debounced function.
* @see https://react-hooks.org/docs/useDebounce
*/
declare function useDebounce<T extends UnknownFunction>(callback: T, wait?: number, options?: DebounceSettings): DebouncedFunc<T>;
//# sourceMappingURL=useDebounce.d.ts.map
declare type UseDebouncedValueOptions = Partial<{
initializeWithNull: boolean;
}>;
declare type UseDebouncedValueReturnType<T> = [
debouncedValue: T | null,
immediatelyUpdateDebouncedValue: Dispatch<SetStateAction<T | null>>
];
/**
* useDebouncedValue
* @param value The value to debounce
* @param timeout The duration to debounce
* @param options The options object.
* @see https://react-hooks.org/docs/useDebouncedValue
*/
declare const useDebouncedValue: <T = unknown>(value: T, timeout: number, options?: UseDebouncedValueOptions) => UseDebouncedValueReturnType<T>;
declare type UseUndoStateOptions = {
maxSize: number;
};
declare type UseUndoStatePushFunctionArgumentsCallback<T> = (currentValue: T) => T;
declare type UseUndoStatePushFunction<T> = (argument: T | UseUndoStatePushFunctionArgumentsCallback<T>) => void;
declare type UndoFunction = () => void;
declare type UseUndoStateReturnValue<T> = [
ExcludeFunction<T>,
UseUndoStatePushFunction<ExcludeFunction<T>>,
UndoFunction
];
declare type CallbackWithNoArguments = () => void;
declare type UseGeolocationReturnType = {
isError: boolean;
lat?: number;
lng?: number;
message: string;
};
/**
* useDidMount hook
* @description Calls a function on mount
*
* @param {Function} callback Callback function to be called on mount
* @see https://react-hooks.org/docs/useDidMount
*/
declare function useDidMount(callback: CallbackWithNoArguments): void;
//# sourceMappingURL=useDidMount.d.ts.map
/**
* useDidUpdate hook
*
* Fires a callback on component update
* Can take in a list of conditions to fire callback when one of the
* conditions changes
*
* @param {Function} callback The callback to be called on update
* @param {Array} conditions The list of variables which trigger update when they are changed
* @see https://react-hooks.org/docs/useDidUpdate
*/
declare function useDidUpdate(callback: () => void, conditions?: unknown[]): void;
//# sourceMappingURL=useDidUpdate.d.ts.map
declare type UseDimensionsRefReturn = {
bottom: number;
height: number;
left: number;
right: number;
top: number;
width: number;
x: number;
y: number;
} | null;
declare type UseDimensionsHook = [
LegacyRef<HTMLDivElement> | undefined,
UseDimensionsRefReturn,
HTMLElement | null
];
declare type UseDimensionsRefArgs = {
updateOnResize?: boolean;
updateOnScroll?: boolean;
};
/**
* useDimensionsRef
* @param updateOnScroll Whether to update on scroll
* @param updateOnResize Whether to update on resize
* @returns [React.Ref<HTMLDivElement>, UseDimensionsRefReturn, HTMLElement | null]
* @see https://react-hooks.org/docs/useDimensionsRef
*/
declare const useDimensionsRef: ({ updateOnScroll, updateOnResize, }?: UseDimensionsRefArgs) => UseDimensionsHook;
/**
* useDocumentEventListener hook
*
* @description A react hook to an event listener to the document
*
* @param {string} eventName The event to track
* @param {Function} callback The callback to be called on event
* @param {ListenerOptions} listenerOptions The options to be passed to the event listener
* @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false
* @see https://react-hooks.org/docs/useDocumentEventListener
*/
declare function useDocumentEventListener(eventName: string, callback: (...args: unknown[]) => void, listenerOptions?: ListenerOptions, isLayoutEffect?: boolean): void;
//# sourceMappingURL=useDocumentEventListener.d.ts.map
/**
* useEffectOnceWhen hook
*
* @description It fires a callback once when a condition is true or become true.
* Fires the callback at most one time.
*
* @param callback The callback to fire
* @param when The condition which needs to be true
* @see https://react-hooks.org/docs/useEffectOnceWhen
*/
declare function useEffectOnceWhen(callback: () => void, when?: boolean): void;
//# sourceMappingURL=useEffectOnceWhen.d.ts.map
/**
* useEventListenerRef hook
*
* A react hook to an event listener to an element
* Returns a ref
*
* @param {string} eventName The event to track`
* @param {Function} callback The callback to be called on event
* @param {object} listenerOptions The options to be passed to the event listener
* @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false
* @returns {Function} A callback ref that can be used as ref prop
* @see https://react-hooks.org/docs/useEventListenerRef
*/
declare function useEventListenerRef(eventName: string, callback: (...args: unknown[]) => void, listenerOptions?: AddEventListenerOptions | EventListenerOptions | boolean, isLayoutEffect?: boolean): (refElement: RefElementOrNull<HTMLElement>) => void;
//# sourceMappingURL=useEventListenerRef.d.ts.map
/**
* useFreshRef
*
* @param value The value which needs to be fresh at all times. Probably
* best used with functions
* @param preferLayoutEffect Should the value be updated using a layout effect
* or a passive effect. Defaults to false.
* @returns A ref containing the fresh value
* @see https://react-hooks.org/docs/useFreshRef
*/
declare function useFreshRef<T>(value: T, preferLayoutEffect?: boolean): MutableRefObject<T>;
//# sourceMappingURL=useFreshRef.d.ts.map
declare type CallbackType<T> = (...args: T[]) => void;
/**
* useFreshTick
* @param callback The callback to be called on mount
* @returns A fresh callback.
* @see https://react-hooks.org/docs/useFreshCallback
*/
declare function useFreshTick<T>(callback: CallbackType<T>): CallbackType<T>;
//# sourceMappingURL=useFreshTick.d.ts.map
declare type EventCallback = (this: Document, event_: unknown) => unknown;
declare type OnChangeEventCallback = (this: Document, event_: unknown, isOpen: boolean) => unknown;
declare type NoopFunction = () => void;
declare type FullscreenApi = {
element: HTMLElement | null | undefined;
exit: NoopFunction | (() => Promise<unknown>);
isEnabled: boolean;
isFullscreen: boolean;
/**
* @deprecated Please use useFullScreen({onChange : function() {}}) instead.
*/
onChange: NoopFunction | ((callback: OnChangeEventCallback) => void);
/**
* @deprecated Please use useFullScreen({onError : function() {}}) instead.
*/
onError: NoopFunction | ((callback: EventCallback) => void);
request: NoopFunction | ((element?: HTMLElement) => Promise<unknown>);
toggle: NoopFunction | ((element?: HTMLElement) => Promise<unknown>);
};
declare type RequestFullscreenOptions = {
navigationUI?: string | "auto" | "hide" | "show";
};
declare type FullScreenOptions = {
onChange?: OnChangeEventCallback;
onError?: EventCallback;
requestFullscreenOptions?: RequestFullscreenOptions;
};
/**
* useFullscreen
* A hook that helps make the document fullscreen
*/
declare function useFullscreen(options?: FullScreenOptions): FullscreenApi;
//# sourceMappingURL=useFullscreen.d.ts.map
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/** Any focusable element, including both HTML and SVG elements. */
interface FocusableElement extends Element, HTMLOrSVGElement {}
/** All DOM attributes supported across both HTML and SVG elements. */
interface DOMAttributes<T = FocusableElement> extends AriaAttributes, DOMAttributes$1<T> {
id?: string | undefined,
role?: AriaRole | undefined,
tabIndex?: number | undefined,
style?: CSSProperties | undefined
}
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
interface FocusEvents {
/** Handler that is called when the element receives focus. */
onFocus?: (e: FocusEvent) => void,
/** Handler that is called when the element loses focus. */
onBlur?: (e: FocusEvent) => void,
/** Handler that is called when the element's focus status changes. */
onFocusChange?: (isFocused: boolean) => void
}
declare type FocusProps = FocusEvents;
interface FocusResult<T> {
/** Props to spread onto the target element. */
focusProps: DOMAttributes<T>;
}
/**
* useFocus
* @description Handles focus events for the immediate target element.
* @see {@link https://react-hooks.org/docs/useFocus}
*/
declare const useFocus: <T extends HTMLElement>(props: FocusProps) => FocusResult<T>;
//# sourceMappingURL=useFocus.d.ts.map
interface FocusWithinProps {
/** Handler that is called when the target element or a descendant receives focus. */
onFocusWithin?: (e: React.FocusEvent) => void;
/** Handler that is called when the target element and all descendants lose focus. */
onBlurWithin?: (e: React.FocusEvent) => void;
/** Handler that is called when the the focus within state changes. */
onFocusWithinChange?: (isFocusWithin: boolean) => void;
}
interface FocusWithinResult<T> {
/** Props to spread onto the target element. */
focusWithinProps: DOMAttributes<T>;
}
/**
* useFocusWithin
* @description Handles focus events for the target component.
* @see {@link https://react-hooks.org/docs/useFocusWithin}
*/
declare const useFocusWithin: <T extends HTMLElement>(props: FocusWithinProps) => FocusWithinResult<T>;
//# sourceMappingURL=useFocusWithin.d.ts.map
/**
* useForkRef
* Joins refs together and returns a combination of the two as a new ref
*
* @param refA
* @param refB
* @returns MutableRefObject
* @see https://react-hooks.org/docs/useForkRef
*/
declare function useForkRef<T>(refA: PossibleRef<T> | null, refB: PossibleRef<T> | null): RefCallback<T> | null;
//# sourceMappingURL=useForkRef.d.ts.map
declare type UseGetIsMounted = () => () => boolean;
/**
* @description useGetIsMounted hook checks if a component is mounted or not at the time.
* Useful for async effects. Returns a callback that returns a boolean representing if the component
* is mounted at the time.
* @returns () => boolean
* @see https://react-hooks.org/docs/useGetIsMounted
*/
declare const useGetIsMounted: UseGetIsMounted;
declare type UseGeoLocationOptions = PositionOptions & {
when?: boolean;
};
/**
* useGeolocation
* Gets the geolocation data as a hook
*
* @param {UseGeoLocationOptions} geoLocationOptions Geolocation options
* @see {@link https://react-hooks.org/docs/useGeolocation}
*/
declare const useGeolocation: (geoLocationOptions?: UseGeoLocationOptions) => UseGeolocationReturnType | null;
//# sourceMappingURL=useGeolocation.d.ts.map
declare type InputChangeEvent = ChangeEvent<HTMLInputElement>;
declare type InputHandler<T> = {
/**
* Function to handle onChange of an input element
*
* @param event The input change event
*/
onChange: (event: InputChangeEvent) => void;
/**
* The current value of the input
*/
value: T;
};
declare type Options<T> = {
/**
* validate
*
* Validator function which can be used to prevent updates
*
* @param {any} New value
* @param {any} Current value
* @returns {boolean} Whether an update should happen or not
*/
validate?: (newValue: T, currentValue: T) => boolean;
};
/**
*
* useInput Hook
*
* Handles an input's value and onChange props internally to
* make text input creation process easier
*
* @param {unknown} [initialValue] Initial value of the input
* @param {Options} [options] Options object
* @returns {InputHandler} Input handler with value and onChange
* @see https://react-hooks.org/docs/useInput
*/
declare function useInput<T extends number | string | readonly string[] | undefined = string>(initialValue?: T, options?: Options<T>): InputHandler<T>;
//# sourceMappingURL=useInput.d.ts.map
/**
* A setInterval hook that calls a callback after a interval duration
* when a condition is true
*
* @param callback The callback to be invoked after interval
* @param intervalDurationMs Amount of time in ms after which to invoke
* @param when The condition which when true, sets the interval
* @param startImmediate If the callback should be invoked immediately
* @see https://react-hooks.org/docs/useIntervalWhen
*/
declare function useIntervalWhen(callback: () => void, intervalDurationMs?: number, when?: boolean, startImmediate?: boolean): void;
//# sourceMappingURL=useIntervalWhen.d.ts.map
/**
*
* useIntersectionObserverRef hook
*
* Returns a mutation observer for a React Ref and fires a callback
*
* @param {IntersectionObserverCallback} callback Function that needs to be fired on mutation
* @param {IntersectionObserverInit} options
* @see https://react-hooks.org/docs/useIntersectionObserverRef
*/
declare function useIntersectionObserverRef(callback: IntersectionObserverCallback | undefined, options?: IntersectionObserverInit): [CallbackRef];
//# sourceMappingURL=useIntersectionObserverRef.d.ts.map
/**
*
* useInViewRef hook
*
* Returns a mutation observer for a React Ref and true/false when element enters/leaves the viewport. Also fires a callback.
*
* @param {IntersectionObserverCallback} callback Function that needs to be fired on mutation
* @param {IntersectionObserverInit} options
* @see https://react-hooks.org/docs/useInViewRef
*/
declare function useInViewRef(callback?: IntersectionObserverCallback, options?: IntersectionObserverInit): [CallbackRef, boolean];
//# sourceMappingURL=useInViewRef.d.ts.map
/**
* useIsomorphicEffect
* Resolves to useEffect when "window" is not in scope and useLayout effect in the browser
*
* @param {Function} callback Callback function to be called on mount
* @see https://react-hooks.org/docs/useIsomorphicEffect
*/
declare const useIsomorphicEffect: typeof useEffect;
//# sourceMappingURL=useIsomorphicEffect.d.ts.map
declare type TrackedKeyEvents = "keydown" | "keypress" | "keyup";
declare type Options$1 = {
/**
* Keyboardevent types to listen for. Valid options are keyDown, keyPress and keyUp
*/
eventTypes?: TrackedKeyEvents[];
/**
* target mutable ref on which the events should be listened. Doesn't work with callback refs.
* Please use useKeyRef instead if you want to use with callback refs.
* If no target is specified, events are listened to on the window. Defaults to window.
*/
target?: RefObject<HTMLElement>;
/**
* Condition which if true, will enable the event listeners
*/
when?: boolean;
};
/**
* useKey hook
*
* Fires a callback on keyboard events like keyDown, keyPress and keyUp
*
* @param {TrackedKeyEvents} keys List of keys to listen for. Eg: ["a", "b"]
* @param {Callback} callback Callback to fire on keyboard events
* @param {Options} options Options
* @see https://react-hooks.org/docs/useKey
*/
declare function useKey(keys: Array<number | string> | number | string, callback: (event: KeyboardEvent) => void, options?: Options$1): void;
//# sourceMappingURL=useKey.d.ts.map
declare type TrackedKeyEvents$1 = "keydown" | "keypress" | "keyup";
declare type Options$2 = {
/**
* Keyboardevent types to listen for. Valid options are keyDown, keyPress and keyUp
*/
eventTypes?: TrackedKeyEvents$1[];
/**
* target ref on which the events should be listened. If no target is specified,
* events are listened to on the window. Only works with object refs. If you want to use with callback refs,
* please use useKeyRef instead.
*/
target?: RefObject<HTMLElement>;
/**
* Condition which if true, will enable the event listeners
*/
when?: boolean;
};
declare type KeyBindings = {
[key: string]: (event: KeyboardEvent) => void;
};
/**
* useKeyBindings
*
* useKeyBindings binds pairs of keyboard events and handlers
*
* @param { KeyBindings } keyBindings
* @param {Options} options
* @see https://react-hooks.org/docs/useKeyBindings
*/
declare const useKeyBindings: (keyBindings: KeyBindings, options?: Options$2 | undefined) => void;
//# sourceMappingURL=useKeyBindings.d.ts.map
declare type TrackedKeyEvents$2 = "keydown" | "keypress" | "keyup";
declare type Callback = (event: KeyboardEvent) => void;
declare type Options$3 = {
/**
* Keyboardevent types to listen for. Valid options are keyDown, keyPress and keyUp
*/
eventTypes?: TrackedKeyEvents$2[];
/**
* Condition which if true, will enable the event listeners
*/
when?: boolean;
};
/**
* useKeyRef hook
*
* Fires a callback on keyboard events like keyDown, keyPress and keyUp
*
* @param {[string|number]} keys List of keys to listen for. Eg: ["a", "b"]
* @param {Function} callback Callback to fire on keyboard events
* @param {Options} options Options
* @returns {CallbackRef} CallbackRef
* @see https://react-hooks.org/docs/useKeyRef
*/
declare function useKeyRef(keys: Array<number | string> | number | string, callback: Callback, options?: Options$3): CallbackRef;
//# sourceMappingURL=useKeyRef.d.ts.map
declare type Options$4 = {
/**
* should the event logging be continuous
*/
continuous?: boolean;
/**
* target ref on which the events should be listened. If no target is specified,
* events are listened to on the document
*/
target?: MutableRefObject<Document> | MutableRefObject<HTMLElement | null>;
/**
* when boolean to enable and disable events, when passed false
* remove the eventlistener if any
*/
when?: boolean;
/**
* opt-in to prevent alert, confirm and prompt from causing the eventlistener to lose track of keyup events.
*/
preventLostKeyup?: boolean;
};
/**
* useKeys hook
*
* @param keysList - list of keys to listen to
* @param callback - callback to be called when a key is pressed
* @param options - options to be passed to the event listener
* @see https://react-hooks.org/docs/useKeys
*/
declare function useKeys(keysList: string[], callback: (event: KeyboardEvent) => void, options?: Options$4): void;
//# sourceMappingURL=useKeys.d.ts.map
/**
* useLifecycleLogger hook
* logs parameters as component transitions through lifecycles
*
* @param componentName Name of the component
* @param {...*} otherArgs Other arguments to log
* @see https://react-hooks.org/docs/useLifecycleLogger
*/
declare const useLifecycleLogger: (componentName?: string, ...otherArgs: unknown[]) => void;
//# sourceMappingURL=useLifecycleLogger.d.ts.map
declare type UseLocalstorageStateReturnValue<S> = [
S,
Dispatch<SetStateAction<S>>,
() => void
];
/**
* useLocalstorageState hook
* Tracks a value within localStorage and updates it
*
* @param {string} key - Key of the localStorage object
* @param {any} initialState - Default initial value
* @see https://react-hooks.org/docs/useLocalstorageState
*/
declare function useLocalstorageState<S>(key: string, initialState?: S | (() => S)): UseLocalstorageStateReturnValue<S>;
//# sourceMappingURL=useLocalstorageState.d.ts.map
/**
* useMapState hook
* A hook to manage state in the form of a map or object.
*
* @param initialValue Initial value of the map
* @see https://react-hooks.org/docs/useMapState
*/
declare function useMapState<T extends {
[key: string]: unknown;
}, K extends keyof T>(initialValue: T): [
T,
{
has: (key: K) => boolean;
remove: (key: K) => void;
removeAll: () => void;
removeMultiple: (...keys: K[]) => void;
set: (key: K, value: T[K]) => void;
setMultiple: (next: Partial<T>) => void;
}
];
//# sourceMappingURL=useMapState.d.ts.map
/**
* useMediaMatch
*
* A react hook that signals whether or not a media query is matched.
*
* @param query The media query to signal on. Example, `"print"` will signal
* `true` when previewing in print mode, and `false` otherwise.
* @returns Whether or not the media query is currently matched.
* @see https://react-hooks.org/docs/useMediaMatch
*/
declare function useMediaMatch(query: string): boolean;
//# sourceMappingURL=useMediaMatch.d.ts.map
/**
* useMergeRefs
* Merges multiple refs into a single function ref.
* Takes any number of refs.
* Refs can be mutable refs or function refs.
*
* @param refs
* @see https://react-hooks.org/docs/useMergeRefs
*/
declare function useMergeRefs<T>(...refs: Array<PossibleRef<T>>): RefCallback<T> | null;
declare type MouseData = {
clientX: number | null;
clientY: number | null;
movementX: number | null;
movementY: number | null;
offsetX: number | null;
offsetY: number | null;
pageX: number | null;
pageY: number | null;
screenX: number | null;
screenY: number | null;
x: number | null;
y: number | null;
};
/**
* useMouse hook
*
* Retrieves current mouse position and information about the position like
* screenX, pageX, clientX, movementX, offsetX
* @see https://react-hooks.org/docs/useMouse
*/
declare function useMouse(): MouseData;
declare type OptionalIndexValue<T> = {
index?: number;
value?: T;
};
declare type OptionalIndicesValues<T> = {
indices?: number[];
values?: T[];
};
declare type UseMultiSelectableListReturnType<T> = [
Array<number[] | T[]>,
{
matchSelection: (parameters: OptionalIndexValue<T>) => boolean;
toggleSelection: (parameters: OptionalIndexValue<T>) => () => void;
updateSelections: ({ indices, values, }: OptionalIndicesValues<T>) => () => void;
}
];
/**
* useMultiSelectableList
* A custom hook to easily select multiple values from a list
*
* @param list - The list of values to select from
* @param initialSelectIndices - The indices of the initial selections
* @param allowUnselected - Whether or not to allow unselected values
* @see https://react-hooks.org/docs/useMultiSelectableList
*/
declare function useMultiSelectableList<T>(list?: T[], initialSelectIndices?: number[], allowUnselected?: boolean): UseMultiSelectableListReturnType<T>;
//# sourceMappingURL=useMultiSelectableList.d.ts.map
/**
*
* useMutationObserver hook
*
* Returns a mutation observer for a React Ref and fires a callback
*
* @param {MutableRefObject<HTMLElement | null>} ref React ref on which mutations are to be observed
* @param {MutationCallback} callback Function that needs to be fired on mutation
* @param {MutationObserverInit} options
* @see https://react-hooks.org/docs/useMutationObserver
*/
declare function useMutationObserver(ref: MutableRefObject<HTMLElement | null>, callback: MutationCallback, options?: MutationObserverInit): void;
//# sourceMappingURL=useMutationObserver.d.ts.map
/**
*
* useMutationObserverRef hook
*
* Returns a mutation observer for a React Ref and fires a callback
*
* @param {MutationCallback} callback Function that needs to be fired on mutation
* @param {MutationObserverInit} options
* @see https://react-hooks.org/docs/useMutationObserverRef
*/
declare function useMutationObserverRef(callback: MutationCallback, options?: MutationObserverInit): [CallbackRef];
//# sourceMappingURL=useMutationObserverRef.d.ts.map
declare type Language = string | null;
/**
* useNavigatorLanguage hook
* Returns the language of the navigator
*
* @returns {Language}
* @see https://react-hooks.org/docs/useNavigatorLanguage
*/
declare function useNavigatorLanguage(): Language;
/**
*
* useOnWindowResize hook
*
* Fires a callback when window resizes
*
* @param {Function} callback Callback to be called before unmount
* @param {boolean} when When the handler should be applied
* @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false
* @see https://react-hooks.org/docs/useOnWindowResize
*/
declare function useOnWindowResize(callback: EventListener, when?: boolean, isLayoutEffect?: boolean): void;
//# sourceMappingURL=useOnWindowResize.d.ts.map
/**
*
* useOnWindowScroll hook
* Fires a callback when window scroll
*
* @param {Function} callback Callback to be called before unmount
* @param {boolean} when When the handler should be applied
* @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false
* @see https://react-hooks.org/docs/useOnWindowScroll
*
*/
declare function useOnWindowScroll(callback: EventListener, when?: boolean, isLayoutEffect?: boolean): void;
//# sourceMappingURL=useOnWindowScroll.d.ts.map
/**
* useOnline hook
*
* Returns true if navigator is online, false if not.
*
* @returns {boolean} The value of navigator.onLine
* @see https://react-hooks.org/docs/useOnline
*/
declare function useOnline(): boolean | null;
//# sourceMappingURL=useOnline.d.ts.map
/**
* useOutsideClick hook
* Checks if a click happened outside a Ref. Handy for dropdowns, modals and popups etc.
*
* @param ref Ref whose outside click needs to be listened to
* @param handler Callback to fire on outside click
* @param when A boolean which which activates the hook only when it is true. Useful for conditionally enable the outside click
* @see https://react-hooks.org/docs/useOutsideClick
* @example
* ```tsx
* import { useOutsideClick } from "./useOutsideClick";
* import { useRef } from "react";
* import { noop } from "../utils/noop";
*
* const MyComponent = () => {
* const ref = useRef<HTMLDivElement>(null);
* const [isOpen, setIsOpen] = useState(false);
* const handleOutsideClick = () => setIsOpen(false);
* useOutsideClick(ref, handleOutsideClick);
* return (
* <div ref={ref}>
* <button onClick={() => setIsOpen(true)}>Open</button>
* {isOpen && (
* <div>Inside</div>
* )}
* </div>
* );
* }
* ```
*/
declare function useOutsideClick(ref: MutableRefObject<HTMLElement | null>, handler: (event: MouseEvent) => void, when?: boolean): void;
//# sourceMappingURL=useOutsideClick.d.ts.map
/**
* useOutsideClickRef hook
* Checks if a click happened outside a Ref. Handy for dropdowns, modals and popups etc.
*
* @param handler Callback to fire on outside click
* @param when A boolean which which activates the hook only when it is true. Useful for conditionally enable the outside click
* @returns An array with first item being ref
* @see https://react-hooks.org/docs/useOutsideClick
*/
declare function useOutsideClickRef(handler: (event: MouseEvent) => void, when?: boolean): [CallbackRef];
//# sourceMappingURL=useOutsideClickRef.d.ts.map
/**
* usePreviousDifferent hook for React
* It returns the past value which was different from the current one.
*
* @param currentValue The value whose previously different value is to be tracked
* @returns The previous value
* @see https://react-hooks.org/docs/usePreviousDifferent
*/
declare function usePreviousDifferent<T>(currentValue: T): T | null;
//# sourceMappingURL=usePreviousDifferent.d.ts.map
/**
* usePreviousImmediate hook for React
*
* @param currentValue The value whose previous value is to be tracked
* @returns The previous value
* @see https://react-hooks.org/docs/usePreviousImmediate
*/
declare function usePreviousImmediate<T>(currentValue: T): T | null;
//# sourceMappingURL=usePreviousImmediate.d.ts.map
/**
* useQueueState
* Manages a queue with react hooks.
* @param initialList Initial value of the list
* @returns The list and controls to modify the queue
* @see https://react-hooks.org/docs/useQueueState
*/
declare function useQueueState<T>(initialList: T[]): [
T[],
{
dequeue: () => T | undefined;
enqueue: (item: T) => number;
length: number;
peek: () => T | undefined;
}
];
//# sourceMappingURL=useQueueState.d.ts.map
/**
*
* useRaf
* Uses a polyfilled version of requestAnimationFrame
*
* @param {Function} callback The callback function to be executed
* @param {boolean} [isActive] The value which while true, keeps the raf running infinitely
* @see https://react-hooks.org/docs/useRaf
*/
declare function useRaf(callback: (timeElapsed: number) => void, isActive: boolean): void;
/**
*
* useResizeObserverRef hook
*
* Returns a resize observer for a React Ref and fires a callback
* https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
*
* @param {ResizeObserverCallback} callback Function that needs to be fired on resize
* @param {ResizeObserverOptions} options An options object allowing you to set options for the observation
* @returns {[CallbackRef]} callbackref
* @see https://react-hooks.org/docs/useResizeObserverRef
*/
declare function useResizeObserverRef(callback: ResizeObserverCallback, options?: ResizeObserverOptions): [CallbackRef];
//# sourceMappingURL=useResizeObserverRef.d.ts.map
/**
* useRenderCount
* @description Get the render count of a component
* @see {@link https://react-hooks.org/docs/useRenderCount}
*/
declare function useRenderCount(): number;
//# sourceMappingURL=useRenderCount.d.ts.map
/**
* useRefElement hook for React
* Helps bridge gap between callback ref and state
* Manages the element called with callback ref api using state variable
* @returns {[RefElementOrNull, (element: HTMLElementOrNull) => void]}
* @see https://react-hooks.org/docs/useRefElement
*/
declare function useRefElement<T>(): [
(refElement: RefElementOrNull<T>) => void,
RefElementOrNull<T>
];
//# sourceMappingURL=useRefElement.d.ts.map
declare type SelectHandler<T> = {
index: number;
item: T;
setIndex: (newIndex: number) => void;
setItem: (newItem: T) => void;
};
/**
* useSelect hook
* Helps easily select a value from a list of values
*
* @param list List of values to select a value from
* @param {number} initialIndex Initial index which is selected
* @returns handler
* @see https://react-hooks.org/docs/useSelect
*/
declare function useSelect<T>(list: T[], initialIndex?: number): SelectHandler<T>;
//# sourceMappingURL=useSelect.d.ts.map
declare type Selection<T> = [number, T];
declare type UseSelectableListReturnType<T> = [
Selection<T>,
{
matchSelection: (parameters: OptionalIndexValue<T>) => boolean;
toggleSelection: (parameters: OptionalIndexValue<T>) => () => void;
updateSelection: (parameters: OptionalIndexValue<T>) => () => void;
}
];
/**
* useSelectableList
* Easily select a single value from a list of values. very useful for radio buttons, select inputs etc.
*
* @param list - The list of values to select from
* @param initialIndex - The index of the initial selection
* @param allowUnselected
* @see https://react-hooks.org/docs/useSelectableList
*/
declare function useSelectableList<T>(list?: T[], initialIndex?: number, allowUnselected?: boolean): UseSelectableListReturnType<T>;
//# sourceMappingURL=useSelectableList.d.ts.map
declare type UseSessionstorateStateReturnValue<S> = [
S,
Dispatch<SetStateAction<S>>,
() => void
];
/**
* useSessionstorageState hook
* Tracks a value within sessionStorage and updates it
*
* @param {string} key - Key of the sessionStorage object
* @param {any} initialState - Default initial value
* @returns {[any, Dispatch<SetStateAction<any>>, () => void]}
* @see https://react-hooks.org/docs/useSessionstorageState
*/
declare function useSessionstorageState<S>(key: string, initialState?: S | (() => S)): UseSessionstorateStateReturnValue<S>;
//# sourceMappingURL=useSessionstorageState.d.ts.map
declare type Add<T> = (...args: Parameters<Set<T>["add"]>) => void;
declare type Delete<T> = (...args: Parameters<Set<T>["delete"]>) => void;
declare type UseSetStateControls<T> = {
add: Add<T>;
delete: Delete<T>;
clear: () => void;
};
declare type UseSetStateReturnValue<T> = [Set<T>, UseSetStateControls<T>];
/**
* useSetState
* @description Manage the state of a Set in React.
* @param {Set<T>} initialSetValue The initial value of the set to manage.
* @returns {UseSetStateReturnValue<T>} The state of the Set and the controls.
* @see {@link https://react-hooks.org/docs/useSetState}
* @example
* import { useSetState } from "./useSetState";
* const [set, setControls] = useSetState(new Set());
* setControls.add(1); // {1}
* setControls.add(2); // {1, 2}
* setControls.delete(1); // {2}
* setControls.clear(); // {}
*
*/
declare function useSetState<T>(initialSetValue: Set<T>): UseSetStateReturnValue<T>;
/**
* useStackState
* @description Manages a stack with react hooks.
* @param initialList Initial value of the list
* @returns The list and controls to modify the stack
* @see https://react-hooks.org/docs/useStackState
*/
declare function useStackState<T>(initialList: T[]): [
T[],
{
clear: () => void;
isEmpty: () => boolean;
length: number;
peek: () => T | undefined;
pop: () => T | undefined;
push: (item: T) => number;
},
T[]
];
//# sourceMappingURL=useStackState.d.ts.map
declare type Callback$1<T> = (...args: T[]) => void;
/**
* useThrottle
* Throttles a function with a timeout and ensures
* that the callback function runs at most once in that duration
*
* @param callback The callback to throttle
* @param timeout Throttle timeout
* @returns [Callback, isReady] The throttled callback and if it is currently throttled
* @see https://react-hooks.org/docs/useThrottle
*/
declare function useThrottle<T>(callback: Callback$1<T>, timeout?: number): [Callback$1<T>, boolean];
//# sourceMappingURL=useThrottle.d.ts.map
/**
* A setTimeout hook that calls a callback after a timeout duration
* when a condition is true
*
* @param callback The callback to be invoked after timeout
* @param timeoutDelayMs Amount of time in ms after which to invoke
* @param when The condition which when true, sets the timeout
* @see https://react-hooks.org/docs/useTimeoutWhen
*/
declare function useTimeoutWhen(callback: () => void, timeoutDelayMs?: number, when?: boolean): void;
//# sourceMappingURL=useTimeoutWhen.d.ts.map
/**
* Use toggle hook helps you easily toggle a value.
*
* @param initialValue Initial value of the toggle, which will be false if not provided.
* @returns [value, setValue]
* @see https://react-hooks.org/docs/useToggle
* @example
* const [boolean, toggle] = useToggle();
* // value is false
* // toggle() will change value to true.
*/
declare function useToggle<S = boolean>(initialValue?: boolean): [S, Dispatch<unknown>];
/**
* Use toggle hook helps you easily toggle a value
*
* @param initialValue Initial value of the toggle, which will be false if not provided.
* @param toggleFunction A toggle function. This allows for non boolean toggles
* @example
* const [value, toggle] = useToggle("on", _value => _value === "on" ? "off" : "on");
* // value is "on"
* // toggle() will change value to "off". Calling it again will change value to "on".
*/
declare function useToggle<S>(initialValue: S, toggleFunction?: Reducer<S, unknown>): [S, Dispatch<unknown>];
/**
* Use toggle hook helps you easily toggle a value
*
* @param initialValue Initial value of the toggle, which will be false if not provided.
* @param toggleFunction A toggle function. This allows for non boolean toggles
* @example
* const [value, toggle] = useToggle("on", _value => _value === "on" ? "off" : "on");
* // value is "on"
* // toggle() will change value to "off". Calling it again will change value to "on".
*/
declare function useToggle<S>(initialValue: S, toggleFunction: ReducerWithoutAction<S>): [S, DispatchWithoutAction];
/**
* useUndoState hook
* Drop in replacement for useState hook but with undo functionality.
*
* @typedef UndoStateOptions
* @type {object}
* @property {number} maxSize - Maximum number of states to keep in the undo stack.
* @param {any} defaultValue - Default value to use for the state. This will be the first value in the undo stack.
* @param {UseUndoStateOptions} options - Options for the undo state. Currently takes the maxSize option.
* @returns {UseUndoStateReturnValue}
* @see https://react-hooks.org/docs/useUndoState
*/
declare const useUndoState: <T>(defaultValue: Exclude<T, UnknownFunction>, options?: UseUndoStateOptions | undefined) => UseUndoStateReturnValue<T>;
//# sourceMappingURL=useUndoState.d.ts.map
declare type Callback$2 = () => void;
/**
* useWillUnmount hook
* Fires a callback just before component unmounts
*
* @param {Function} callback Callback to be called before unmount
* @see https://react-hooks.org/docs/useWillUnmount
*/
declare function useWillUnmount(callback: Callback$2): void;
//# sourceMappingURL=useWillUnmount.d.ts.map
/**
* useWindowEventListener hook
*
* A react hook to an event listener to the window
*
* @param {string} eventName The event to track
* @param {Function} callback The callback to be called on event
* @param {ListenerOptions} listenerOptions The options to be passed to the event listener
* @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false
* @returns {undefined}
* @see https://react-hooks.org/docs/useWindowEventListener
*/
declare function useWindowEventListener(eventName: string, callback: (...args: unknown[]) => void, listenerOptions?: ListenerOptions, isLayoutEffect?: boolean): void;
//# sourceMappingURL=useWindowEventListener.d.ts.map
declare type ScrollPosition = {
scrollX: Window["scrollX"];
scrollY: Window["scrollY"];
};
/**
*
* useWindowScrollPosition hook
* A React hook to get the scroll position of the window
*
* @returns an object containing scrollX and scrollY values
* @see https://react-hooks.org/docs/useWindowScrollPosition
*/
declare function useWindowScrollPosition(): ScrollPosition;
//# sourceMappingURL=useWindowScrollPosition.d.ts.map
declare type WindowDimensions = DeepNullable<Pick<Window, "innerHeight" | "innerWidth" | "outerHeight" | "outerWidth">>;
/**
* useWindowSize hook
* A hook that provides information of the dimensions of the window
*
* @returns Dimensions of the window
* @see https://react-hooks.org/docs/useWindowSize
*/
declare function useWindowSize(): WindowDimensions;
export { useArrayState, useAsyncEffect, useBoundingclientrect, useBoundingclientrectRef, useCountdown, useCounter, useDebounce, useDebouncedValue, useDidMount, useDidUpdate, useDimensionsRef, useDocumentEventListener, useEffectOnceWhen, useEventListenerRef, useFocus, useFocusWithin, useForkRef, useFreshRef, useFreshTick, useFullscreen, useGeolocation, useGetIsMounted, useInViewRef, useInput, useIntersectionObserverRef, useIntervalWhen, useIsomorphicEffect, useKey, useKeyBindings, useKeyRef, useKeys, useLifecycleLogger, useLocalstorageState, useMapState, useMediaMatch, useMergeRefs, useMouse, useMultiSelectableList, useMutationObserver, useMutationObserverRef, useNavigatorLanguage, useOnWindowResize, useOnWindowScroll, useOnline, useOutsideClick, useOutsideClickRef, usePreviousDifferent, usePreviousImmediate, useQueueState, useRaf, useRefElement, useRenderCount, useResizeObserverRef, useSelect, useSelectableList, useSessionstorageState, useSetState, useStackState, useThrottle, useTimeoutWhen, useToggle, useUndoState, useWillUnmount, useWindowEventListener, useWindowScrollPosition, useWindowSize };