Skip to content

nDriaDev/react-tools

Repository files navigation


logo
React-Tools

A collection of Hooks, Components, Utilities and Types for React

npm version npm bundle size (scoped version) npm NPM

Summary

Features

  • Typescript
    • Written in typescript for type safety.
  • Tree Shakable
    • Import only that you use. Indivual import cost is tiny.
  • Demos
    • All implementations have a demo that allow you to try them.

Demo

Go to Demo to see and try all implementations.

Tools

HOOKS

STATE

createPubSubStore

A state management hook implemented on Publish-Subscribe pattern. It allows components to subscribe to state changes and receive updates whenever the state is modified, providing a scalable and decoupled state management solution.N.B.: to work properly, objects like Set, Map, Date or more generally objects without Symbol.iterator must be treated as immutable. See demo

createPubSubStore<T extends object, E extends Record<string, (store: T, ...args: any) => void>>(obj: T, mutatorsFn?: E, persist?: boolean): { getStore: () => T; mutateStore: (cb: (globStore: T) => void) => void; mutators: Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>, usePubSubStore: { (subscribe?: undefined): [T, (store: T | ((currStore: T) => T)) => void, () => T, Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>]; <C>(subscribe?: (store: T) => C): [C, (store: C | ((currStore: C) => C)) => void, () => C, Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>]; <C>(subscribe?: (store: T) => C): [T | C, (store: T | C | ((currStore: T) => T) | ((currStore: C) => C)) => void, () => T, Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>] }}

useArray

Hook to use Array data structure to handle component state with all Array methods. See demo

useArray<T>(initialState?: Array<T> | (() => Array<T>))

useDerivedState

Hook useful when the internal state of a component depends on one or more props. It receives an initial state and a dependency array that works the same way as that of a useEffect, useMemo, and useCallback. Every time the dependencies change, the derived state is resetted to initial state. A third optional parameter can be passed, to execute a compute function after the dependencies are updated, without having a useEffect within the component. See demo

useDerivedState<T>(initialState: T | (() => T), deps: DependencyList, compute?: EffectCallback): [T, Dispatch<SetStateAction<T>>]

useLocalStorageState

Custom useState hook implementation using LocalStorage, with immutable getter state function and to remove key from localStorage. See demo

useLocalStorageState<T>({ key, initialState, opts }: { key: string, initialState?: T | (() => T), opts?: { serializer?: (item: T) => string, deserializer?: (item: string) => T, mode?: "read" | "write" | "read/write" } }): [T, () => T, () => void] | [Dispatch<SetStateAction<T>>, () => T, () => void] | [T, Dispatch<SetStateAction<T>>, () => T, () => void]

useMap

Hook to use Map data structure to handle component state with all Map methods. See demo

useMap<K, V>(initialState?: Iterable<readonly [K, V]> | (() => Iterable<readonly [K, V]>))

usePrevious

It's track the previous value of a variable, with possibility to enable/disable tracking. See demo

usePrevious<T = unknown>(variable: T): [T|undefined, (enable: boolean) => void]

useProxyState

Hook to handle component state that allows you to use an object for your state and mutating it in a way more idiomatic for JS. N.B. not destructure state, otherwise break changes updated. See demo

useProxyState<T extends Record<string, any>>(initialState: T | (() => T), proxyInDepth:boolean=false): T

useReducerGetReset

Custom useReducer with get and reset state functions. See demo

useReducerGetReset<R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, initializer?: (init: ReducerState<R>) => ReducerState<R>): [ReducerState<R>, Dispatch<ReducerAction<R>>, ()=>ReducerState<R>, ()=>void]

useReducerHistory

Custom useReducer that tracks and allows to use previous values. See demo

useReducerHistory<R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, initializer?: (init: ReducerState<R>) => ReducerState<R>, capacity: number | "no-limit" = "no-limit"): [ReducerState<R>, Dispatch<ReducerAction<R>>, { history: readonly ReducerState<R>[], presentPointer: number, trackUpdate: (enable: boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: ReducerAction<R>) => void }]

useReducerHistoryGetter

Custom useReducer with getter state function and that tracks and allows to use previous values. See demo

useReducerHistoryGetter<R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, initializer?: (init: ReducerState<R>) => ReducerState<R>, capacity: number | "no-limit" = "no-limit"): [ReducerState<R>, Dispatch<ReducerAction<R>>,()=>ReducerState<R>, { history: readonly ReducerState<R>[], presentPointer: number, trackUpdate: (enable: boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: ReducerAction<R>) => void }]

useSessionStorageState

Custom useState hook implementation using sessionStorage, with immutable getter state function and to remove key from sessionStorage. See demo

useSessionStorageState<T>({ key, initialState, opts }: { key: string, initialState?: T | (() => T), opts?: { serializer?: (item: T) => string, deserializer?: (item: string) => T, mode?: "read" | "write" | "read/write" } }): [T, () => T, () => void] | [Dispatch<SetStateAction<T>>, () => T, () => void] | [T, Dispatch<SetStateAction<T>>, () => T, () => void]

useSet

Hook to use Set data structure to handle component state with all Set methods. See demo

useSet<T>(initialState?: Iterable<T> | (() => Iterable<T>))

useStateGetReset

Custom useState with get and reset state functions. See demo

useStateGetReset<T>(initialState: T | (() => T)): [T, Dispatch<SetStateAction<T>>, () => T, () => void]

useStateHistory

Custom useState that tracks and allows to use previous values. See demo

useStateHistory<T>(initialState: T | (() => T), capacity: number | "no-limit" = "no-limit"): [T, Dispatch<SetStateAction<T>>, { history: readonly T[], presentPointer: number, trackUpdate: (enable:boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: T) => void }]

useStateHistoryGetter

Custom useState with getter state function and that tracks and allows to use previous values. See demo

useStateHistoryGetter<T>(initialState: T | (() => T), capacity: number | "no-limit" = "no-limit"): [T, Dispatch<SetStateAction<T>>, () => T, ReturnType<typeof useStateHistory<T>>[2]]

useStateValidator

Custom useState hook that validates state on every update. See demo

useStateValidator<T>(initialState: T | (() => T), validator: StateValidator<T>): [T, Dispatch<SetStateAction<T>>, T extends object ? {[k in keyof T]:{invalid: boolean, message?: string}} : {invalid: boolean, message?: string}]

useSyncExternalStore

useSyncExternalStore hook polyfilled for React versions below 18 only client side. See demo

useSyncExternalStore<Snapshot>(subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => Snapshot): Snapshot

LIFECYCLE

useDeferredValue

useDeferredValue hook polyfilled for React versions below 18. See demo

useDeferredValue<T>(value: T): T

useEffectCompare

Custom useEffect that reexecutes EffectCallback only when comparator function, received as third parameter, returns true. See demo

useEffectCompare<T = unknown>(cb: EffectCallback, deps: DependencyListTyped<T>, compareFn?: CompareFn<T>)

useEffectDeepCompare

Custom useEffect that reexecutes EffectCallback only when deps are different in depth. See demo

useEffectDeepCompare(cb: EffectCallback, deps: DependencyList):void

useEffectOnce

Hook to executes effect and clean up after component mount only once. It prevents React 18 StrictMode behavior if present, otherwise it works like a normal useEffect with empty dependencies array. N.B. Not use in a component with normal useEffect, if it executes a React.DispatchAction, because this action is executes twice if there is React.StrictMode. See demo

useEffectOnce(effect: EffectCallback)

useIsMounted

Hoos to know when a component is mounted or not. See demo

useIsMounted(): ()=>boolean

useLayoutEffectCompare

Custom useLayoutEffect that reexecutes EffectCallback only when comparator function, received as third parameter, returns true. See demo

useLayoutEffectCompare<T = unknown>(cb: EffectCallback, deps: DependencyListTyped<T>, compareFn?: CompareFn<T>)

useLayoutEffectDeepCompare

Custom useEffect that reexecutes EffectCallback only when deps are different in depth. See demo

useLayoutEffectDeepCompare(cb: EffectCallback, deps: DependencyList):void

useLayoutEffectOnce

Hook to executes effect and clean up after component mount only once. It prevents React 18 StrictMode behavior if present, otherwise it works like a normal useLayoutEffect with empty dependencies array. N.B. Not use in a component with normal useLayoutEffect, if it executes a React.DispatchAction, because this action is executes twice if there is React.StrictMode. See demo

useLayoutEffectOnce(effect: EffectCallback)

useLogger

Hook to log componet details during Lifecycle events. See demo

useLogger(name: string, props: object)

useRerender

Hook that force a render. See demo

useRerender(): React.DispatchWithoutAction

PERFORMANCE

useCallbackCompare

Custom useCallback that returns memoized callback that changes only when comparator function, received as third parameter, returns true. See demo

useCallbackCompare<T extends Function, E = unknown>(cb: T, deps: DependencyListTyped<E>, compareFn?: CompareFn<E>):T

useCallbackDeepCompare

Custom useCallback that returns memoized callback that changes only if deps are different in depth. See demo

useCallbackDeepCompare<T extends Function>(cb: T, deps: DependencyList):T

useId

useId hook polyfilled for React versions below 18: not use for key prop. See demo

useId(): string

useLazyRef

Hook that works 'partially' like the useState hook with lazy initialization: ensures that the initializer function is executed only once. See demo

useLazyRef<T>(initializer: () => T): React.MutableRefObject<T>

useMemoCompare

Custom useMemo that returns memoized value that changes only when comparator function, received as third parameter, returns true. See demo

useMemoCompare<T = unknown, E = unknown>(cb: () => T, deps: DependencyListTyped<E>, compareFn?: CompareFn<E>):T

useMemoDeepCompare

Custom useMemo that returns memoized value that changes only if deps are different in depth. See demo

useMemoDeepCompare<T=unknown>(cb: () => T, deps: DependencyList):T

useMemoizedFn

Hook to store a function that will never change while keeping its dependencies always up to date. Can be used instead of useCallback, without esplicity dependencies array. See demo

useMemoizedFn<T extends (...args: any[]) => any>(fn: T)

useMergedRef

Hook to merge multiple refs into one. See demo

useMergedRef<T>(...refs: Ref<T>[]): Ref<T>

EVENTS

useBeforeUnload

Hook to handle beforeunload event. See demo

useBeforeUnload({element, listener, opts}:{ element?: RefObject<HTMLElement> | Window | undefined, listener: (evt: BeforeUnloadEvent) => void, opts?: boolean | AddEventListenerOptions}): ()=>void

useClickOutside

Hook to listen and execute an action when there is a click outside an element. See demo

useClickOutside(target: RefObject<HTMLElement> | HTMLElement, handler: (evt: Event) => void):void

useContextMenu

Hook to add contextmenu event listener. The contextmenu event fires when the user attempts to open a context menu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key. See demo

useContextMenu({ element, listener, effectType, listenerOpts }: { element: RefObject<HTMLElement> | Window, listener: (evt: PointerEvent) => void | Promise<void>, effectType?: "normal" | "layout", listenerOpts?: boolean | AddEventListenerOptions | undefined })

useDocumentVisibility

Hook to track document visibility. Refers to Document VisibilityState. See demo

useDocumentVisibility(): DocumentVisibilityState

useDoubleClick

Hook to handle double click event. Double clicking in react as well as with vanilla js, it is possible to manage it but it is not possible to have both managers on the same element. Thanks to this hook it is possible to do this, and it works with all events that can be associated with a user click (for example mousedown but also touchstart). See demo

useDoubleClick<T extends Element = Element, E extends Event = Event>(handler: ((evt: SyntheticEvent<T, E>) => Promise<void> | void) | { doubleClick: (evt: SyntheticEvent<T, E>) => Promise<void> | void, singleClick?: (evt: SyntheticEvent<T, E>) => Promise<void> | void, tolerance?: number }): ((evt: SyntheticEvent<T, E>) => Promise<void> | void)

useEventDispatcher

Hook to dispatch an Event or a CustomEvent. See demo

useEventDispatcher(element: RefObject<HTMLElement> | Window = window): (evt: Event | CustomEvent) => void

useEventListener

Hook to simplify add and remove EventListener use. It's persist during rerendering and automatically remove eventlistener on unMount component lifecycle. See demo

useEventListener<T extends keyof WindowEventMap, E extends Element>({ type, listener, element = window, listenerOpts, effectType = "normal" }: { type: T|(T[]), listener: ((evt: WindowEventMap[T]) => unknown | Promise<unknown>), element?: RefObject<E> | E | Window, listenerOpts?: boolean | AddEventListenerOptions, effectType?: "normal" | "layout" }): (() => void)

useEvents

Communication system based on Events pattern implemented on a EventTarget subclass. AddListener and dispatch functions to communicate. The result of invoking the addListener function in turn returns a function that can be used to removeListener on event. Otherwise, the listener is automatically removed when the component that has instantiated it is unmounted. See demo

useEvents(): [(type: string, callback:<T>(evt: Event|CustomEvent<T>) => void, options?: boolean | AddEventListenerOptions) => ()=>void, <T>(evt: Event|CustomEvent<T>) => void]

useHotKeys

Hook to listen for the keyboard press, support key combinations, built on hotKeyHandler utility function. See demo

useHotKeys({ hotKey, type = "keydown", target = window, listener, listenerOpts }: { hotKey: `${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}`, type?: "keydown" | "keyup", target?: RefObject<HTMLElement> | Window, listener: (evt: KeyboardEvent | KeyEvt<HTMLElement>) => void | Promise<void>, listenerOpts?: boolean | AddEventListenerOptions }): (() => void)

useHover

Hook that determines whether the item is hovered or not and handles state hovers. See demo

useHover(target: RefObject<HTMLElement> | HTMLElement, opts?: { onEnter?: (evt: Event) => void, onChange?: (isHover: boolean) => void, onLeave?: (evt: Event) => void, returnValue?: boolean }): boolean | void

useInfiniteScroll

Hook to deal with large sets of data. It allow users to scroll through content endlessly without explicit pagination or loading new pages. See demo

useInfiniteScroll<T, E extends Element>({ request, ref, hasMoreData, threshold, onBefore, onError, onSuccess }: { request: (data?: T) => Promise<T>, ref: RefObject<E>, hasMoreData: (data?: T) => boolean, threshold?: number, onBefore?: () => void, onSuccess?: () => void, onError?: (err: unknown) => void }): { data: T | undefined, loading: boolean, fullData: boolean, updateData: (data: T | ((currentState?: T) => T)) => void, loadData: () => Promise<void> }

useIntersectionObserver

Hook to use Intersection Observer. Refer to Intersection Observer API. See demo

useIntersectionObserver<T extends Element>(cb: IntersectionObserverCallback, opts?: IntersectionObserverInit):[RefCallback<T>, () => void, () => void]

useIsOnline

Hook to detect network connection status. See demo

useIsOnline(): boolean

useLongPress

Hook to execute a callback on a long press event. See demo

useLongPress<T extends Element = Element, E extends Event = Event>(cb: useLongPressCallback<E>, { duration = 1000, normalPress, onStart, onFinish }: useLongPressOptions<E>): RefCallback<T>

useMeasure

Hook to measure and track element's dimensions. See demo

useMeasure<T extends Element>(): [React.RefCallback<T>, DOMRectReadOnly]

useMouse

Hook to track mouse position also in relationship with an element. It works with pointerEvents. See demo

useMouse(opts: { type?: "client" | "page" | "screen", relativeElement?: RefObject<HTMLElement | null> | HTMLElement } = { type: "client" }): { x: number | null, y: number | null } | { x: number | null, y: number | null, relativeElementDim?: DOMRect }

useMutationObserver

Hook to use Mutation Observer. Refer to Mutation Observer API. See demo

useMutationObserver<T extends Element>(cb: MutationCallback, opts?: MutationObserverInit): [RefCallback<T>, () => void, () => void, () => MutationRecord[] | undefined]

useNetwork

Hook to detect network connection infos, refer to Network Information API. It takes optinally a parameter selectedInfo to specify a subset of connection status property. See demo

useNetwork<T extends keyof ConnectionState>(selectedInfo?: ArrayMinLength1<T>): ConnectionState | {[k in T] : ConnectionState[k]}

usePerformAction

Hook that executes a callback after a render. See demo

usePerformAction<T extends (...args: unknown[]) => void>(cb: T): (...args: Parameters<T>) => void

usePinchZoom

Hook to handle pinch zoom gestures. See demo

usePinchZoom({ target = window, listener }: { target?: RefObject<HTMLElement> | Window, listener: (evt: PointerEvent, type: "zoomIn" | "zoomOut") => void | Promise<void> }): (()=>void)

usePointerLock

Hook to use PointerLock API. See demo

usePointerLock<T extends HTMLElement>({ target, unadjustedMovement, onLock, onUnlock, onError }: UsePointerLockProps<T>): UsePointerLockResult

useResizeObserver

Hook to use Resize Observer. Refer to Resize Observer API. See demo

useResizeObserver<T extends Element>(cb: ResizeObserverCallback, opts?: ResizeObserverOptions):[RefCallback<T>, () => void, () => void]

useResponsive

Hook for getting responsive window size. See demo. It receives an optional param config to manually setting breakpoint keys. config can have a keys subset and value can be a number or an object with value and condition properties. If value is a number, the condition will be ">". By default Breakpoints are:

  • xs: { value: 576, condition: "<" }
  • sm: { value: 576, condition: ">=" }
  • md: { value: 768, condition: ">=" }
  • lg: { value: 992, condition: ">=" }
  • xl: { value: 1200, condition: ">=" }
useResponsive<T extends UseResponsiveKeys>(config?: UseResponsiveBreakpoints<T>): { [s in (keyof typeof defaultConfig)]: boolean } | { [s in UseResponsiveKeys<T>]: boolean }

useScreen

Hook to work with Screen Orientation API and Window Management API. See demo

useScreen(allScreen?:boolean): [ScreenDetails, (orientation: OrientationLockType) => Promise<void>, ()=>void]

useScrollIntoView

Hook to scroll an element into view. See demo

useScrollIntoView<T extends Element, E extends Element | null = null>({ duration = 1000, axis = "y", animation = easeInOutSine, offset = 0, cancelable = false, onFinish, scrollableElement }: { duration?: number, axis?: "x" | "y", animation?: (t: number) => number, offset?: number, cancelable?: boolean, onFinish?: () => void, scrollableElement: (()=>E)|E|React.RefObject<E|null> }): { targetRef: React.MutableRefObject<T | null>, scroll: (alignment?: "start" | "center" | "end") => void, cancel: () => void }

useSwipe

Hook to handle swipe gesture. See demo

useSwipe({ target, onSwipeStart, onSwipe, onSwipeEnd, options }: UseSwipeProps): UseSwipeResult

useVisible

Hook to know if an element is visible and optionally the visible area ration of the element. See demo

useVisible<T extends Element>(opts?: IntersectionObserverInit & { withRatio?: boolean }): [RefCallback<T>, boolean] | [RefCallback<T>, boolean, number]

API DOM

useActiveElement

Hook that returns activeElement and listen its changes. See demo

useActiveElement():Element|null

useAnimation

Hook to use Web Animations API. See demo

useAnimation<T extends Element>({ keyFrames, immediate, opts, onCancel, onFinish, onRemove, onError }: UseAnimationProps): UseAnimationResult<T>

useAudio

Hook to use an HTML audio element. See demo

useAudiocreateHTMLMediaHook<HTMLAudioElement>("audio");

useBattery

Hook for accessing and monitoring device battery status. Refer to Battery Status API. See demo

useBattery(opts?: { onChargingChange?: (evt: Event) => void, onChargingTimeChange?: (evt: Event) => void, onDischargingTimeChange?: (evt: Event) => void, onLevelChange?: (evt: Event) => void }): BatteryStatus

useBluetooth

Hook to use Web Bluetooth API. See demo

useBluetooth():[{isSupported: boolean, isConnected: boolean, device: BluetoothDevice|null, server: BluetoothRemoteGATTServer|null}, (opts?: BluetoothDevicesOptions)=>Promise<void>]

useBroadcastChannel

Hook to use Broadcast Channel API. See demo

useBroadcastChannel<T>(name: string, onMessage?: (evt:MessageEvent<T>)=>void, onError?: (evt: MessageEvent)=>void):[T|undefined, (data:T)=>void]

useClipboard

Hook to handle Clipboard. Refers to Clipboard API. N.B.: The hook has the same compatibility issues as the Clipboard API for Firefox, i.e. it is currently impossible to read from the clipboard. See demo

useClipboard({ useValue, dataType, target }: { useValue: boolean, dataType: "text" | "any", target?: RefObject<HTMLElement> | HTMLElement }): [string, (text: string) => Promise<void>, () => Promise<string>] | [string | Blob | (string | Blob)[], (blob: Blob | Blob[]) => Promise<void>, () => Promise<string | Blob | (string | Blob)[]>] | [(text: string) => Promise<void>, () => Promise<string>] | [(blob: Blob | Blob[]) => Promise<void>, () => Promise<string | Blob | (string | Blob)[]>]

useColorScheme

Hook to handle ColorScheme. See demo

useColorScheme({ defaultValue, getter, setter, returnValue }: { defaultValue: "dark" | "light" | "mediaQuery", getter?: () => "dark" | "light" | null | undefined, setter?: (schema: "light"|"dark") => void, returnValue: boolean }): ["light" | "dark", (schema: "light" | "dark") => void] | ((schema: "light" | "dark") => void)

useDebounce

Hook to delay a function execution with possibility to cancel execution and to invoke them immediately. See demo

useDebounce<T extends unknown[]>(fn: (...args: T)=>void, opts: { delay: number, focusedWindow?: boolean }): [(...args: T) => void, () => void, (...args: T) => void]

useDeviceMotion

Hook to handle device motion. See demo

useDeviceMotion(): DeviceMotionProps

useDeviceOrientation

Hook to handle device orientation. See demo

useDeviceOrientation(): DeviceOrientationProps

useDialogBox

Hook to use Dialog Box prompt, alert or confirm. See demo

useDialogBox(type: "prompt" | "confirm" | "alert"): ((message?: string, _default?: string) => string | null) | ((message?: any) => void) | ((message?: string) => boolean)

useDisplayMedia

Hook to capture the contents of a display. See demo

useDisplayMedia(): [MediaStream | undefined, (options?: TDisplayMediaStreamOptions) => Promise<void>, () => void]

useDocumentPIP

Hook to use Document PIP (Document-Picture-in-Picture API). See demo

useDocumentPIP({ options: { inheritCSS, window: wind } = { window: { height: 300, width: 450 } }, onOpen, onOpened, onClose, onError }: UseDocumentPIPProps): UseDocumentPIPResult

useEventSource

Hook to handle an EventSource or Server-Sent-Events connection to an HTTP server, which sends events in text/event-stream format. See demo

useEventSource<T>({ url, opts, events, immediateConnection, onOpen, onError, onMessage }: UseEventSourceProps): UseEventSourceResult<T>

useEyeDropper

Hook to use EyeDropper API. See demo

useEyeDropper({ onStart, onFinish }: { onStart?: () => void, onFinish?: (result: `#${string}`) => void } = {})

useFPS

Hook to detect FPS (Frames per second). See demo

useFPS({ everySeconds, windowSize }:UseFPSProps={windowSize:10, everySeconds:.5}): UseFPSResult

useFetch

Hook to use Fetch API with more control and the possibility to execute request with suspense support. See demo

useFetch<T>(url: RequestInfo | URL, { suspensable, onError, onLoading, ...rest }: RequestInit & { suspensable?: boolean, onLoading?: (loading: boolean) => void, onError?: (err: unknown) => void } = {}): [T|undefined, (conf?: RequestInit) => Promise<void>, boolean, unknown]

useFullscreen

Hook to use Fullscreen API. See demo

useFullscreen<T extends Element>(onEnter?: () => void|Promise<void>, onChange?: (evt: Event) => void, onExit?: () => void|Promise<void>): [boolean, RefCallback<T>, (opts?: FullscreenOptions) => Promise<void>, () => Promise<void>]

useGeolocation

Hook to use user's geographic location. Refer to GeoLocation API. See demo

useGeolocation({mode, locationOptions, onError}: { locationOptions?: PositionOptions, mode: "observe" | "current" | "manual", onError?: (error: GeolocationPositionError) => void }): [GeoLocationObject, ()=>Promise<void>, ()=>Promise<()=>void>]

useIdleCallback

Hook to invoke a callback when the browser is idle. Refer to requestIdleCallback in React. The options parameter differs from IdleRequestOptions type: it adds the possibility to pass another property unsupportedBehavior to specify what do if requestIdleCallback is not supported. See demo

useIdleCallback(cb: (deadline?: IdleDeadline | DOMHighResTimeStamp | void) => void, opts?: {timeout: number , unsupportedBehavior?: "animationFrame" | "timeout" | "immediatly" }): [boolean, () => void, () => void]

useInterval

Hook to handle setInterval timer function with the possibility to clear and promisify execution. See demo

useInterval<TArgs extends unknown[]>(callback: (...args: TArgs) => void, delay: number): [(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>]

useLock

Hook to use Web Locks API. See demo

useLock<T>(name?: string, cb?: LockGrantedCallback, opts?: LockOptions): [(currName?: string, currCb?: LockGrantedCallback, currOpts?: LockOptions) => Promise<T>, () => Promise<LockManagerSnapshot>]

useMediaDevices

Hook to use MediaDevices interface methods, that give access to any hardware source of media data. See demo

useMediaDevices(action: UseMediaDevicesProps): UseMediaDevicesResult

useMediaQuery

Hook to handle CSS mediaQuery. It returns an object with matches and media properties and receives an optional onChange function to handle MediaQueryListEvent change event. See demo

useMediaQuery(mediaQuery: string, onChange?: (evt: MediaQueryListEvent) => void ): {matches: boolean, media: string}

usePIP

Hook to use PIP (Picture-in-Picture API). See demo

usePIP({ onOpen, onOpened, onClose, onError, target }: UsePIPProps): UsePIPResult

usePermission

Hook to query the status of API permissions attributed to the current context. Refer to PermissionAPI. See demo

usePermission(permission: TPermissionName): UsePermissionResult

usePopover

Hook to use Popover API. See demo

usePopover({ mode, onBeforeToggle, onToggle }: UsePopoverProps): UsePopoverResult

usePromiseSuspensible

Hook to resolve promise with Suspense support. The component that uses it, it need to be wrapped with Suspense component. This hook can be used in conditional blocks. See demo

usePromiseSuspensible<T>(promise: ()=>Promise<T>, deps: DependencyList, options: { cache?: "unmount" | number, cleanOnError?: boolean } = {}): Awaited<ReturnType<typeof promise>>

usePublishSubscribe

Communication system based on PubSub pattern. Instantiate a topic and use the publish and subscribe functions to communicate. See demo

usePublishSubscribe<T>(topic: string): [(listener: (value?: T) => Promise<void> | void) => () => void, (value?: T) => Promise<void> ]

useRaf

Hook to execute a callback function with requestAnimationFrame to optimize performance. Refer to (requestAnimationFrame)[https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame]. See demo

useRaf<T extends unknown[]>(cb: (timer: number, repeat: ()=>void, ...args: T) => void): [(...args: T)=>void, ()=>void]

useReducedMotion

Hook to detect if user prefers to reduce motion. See demo

useReducedMotion(): boolean

useRemotePlayback

Hook to use RemotePlayback API. See demo

useRemotePlayback<T extends HTMLMediaElement>({ onConnecting, onConnect, onDisconnect, onError }: UseRemotePlaybackProps={}): UseRemotePlaybackResult<T>

useScreenWakeLock

Hook to use Screen Wake Lock API. See demo

useScreenWakeLock(onRelease?: (evt?: Event) =>void): [{isSupported: boolean, type: "screen"|null, isActive: boolean|null}, ()=>Promise<void>, ()=>Promise<void>]

useScript

Hook to dinamically load an external script like Google Analitycs. See demo

useScriptuseScript: UseScript = function (attributes, options)

useShare

Hook to use Web Share Api. See demo

useShare(): {isSupported: boolean, share: (data?: ShareData)=>Promise<void>}

useSpeechRecognition

Hook to use SpeechRecognition API. Refer to Web Speech API. See demo

useSpeechRecognition({ alreadyStarted, defaultConfig, onAudioStart, onAudioEnd, onEnd, onError, onNoMatch, onResult, onSoundStart, onSoundEnd, onSpeechStart, onSpeechEnd, onStart }: UseSpeechRecognitionProps): [SpeechRecognitionState, (config?: SpeechRecognitionConfig) => void, () => void, (resultAlso?: boolean) => void]

useSpeechSynthesis

Hook to use SpeechSynthesis API. Refer to Web Speech API. See demo

useSpeechSynthesis(opts?: UseSpeechSynthesisProps): ReturnType<UseSpeechSynthesis>

useTextSelection

Hook to track text selection. Refers to Selection API. See demo

useTextSelection({ target, onStart, onChange, onEnd }: { target?: RefObject<HTMLElement> | HTMLElement, onStart?: (evt: Event) => void, onChange?: (evt: Event) => void, onEnd?: (evt: Event) => void } = {}): TextSelection | null

useThrottle

Hook to limit function execution frequency. See demo

useThrottle<T extends unknown[]>(fn: (...args: T) => void | Promise<void> , opts: { delay?: number, waitFn?: boolean }): [(...args: T) => void, () => void, (...args: T) => void]

useTimeout

Hook to handle setTimeout timer function with the possibility to clear and promisify execution. See demo

useTimeout<TArgs extends unknown[]>(callback: (...args: TArgs) => void, delay: number): [(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>]

useTitle

Hook to handling app page title. It works outside Component also and it returns array of two functions to read and write title. See demo

useTitle(title?: string): [() => string, (title: string) => void]

useVibrate

Hook to use device vibration hardware. See demo

useVibrate():{isSupported: boolean, vibrate: ((pattern: number | number[]) => void), cancel: ()=>void}

useVideo

Hook to use an HTML video element. See demo

useVideocreateHTMLMediaHook<HTMLVideoElement>("video");

useWebSocket

Hook for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. See demo

useWebSocket<T = string | ArrayBuffer | Blob> ({ url, protocols, binaryType, onOpen, onMessage, onError, onClose, immediateConnection, bufferingData, autoReconnect }: UseWebSocketProps): UseWebSocketResult<T>

useWebWorker

Hook to use Web Worker, handling registration and communication. See demo

useWebWorker({ url, options, onMessage, onError, onMessageError }: UseWebWorkerProps): UseWebWorkerResult

useWebWorkerFn

Hook to run expensive functions using a Web Worker without blocking the UI handling execution as Promise. See demo

useWebWorkerFn<T extends (...args: unknown[]) => unknown>(fn: UseWebWorkerFnProps<T>["fn"], deps?: UseWebWorkerFnProps<T>["deps"]): UseWebWorkerFnResult<T>

COMPONENTS

ErrorBoundary

Wrapper component that lets you display some fallback UI when your application throws an error during rendering. See demo

class ErrorBoundary extends Component<PropsWithChildren<{ onCatch?: (error: Error, info: ErrorInfo) => void, fallback?: ReactNode | ((error: Error, info: ErrorInfo, retry: () => void) => ReactNode) | ((props: { error: Error, info: ErrorInfo, retry: () => void })=>JSX.Element)}>, { hasError: boolean, error?:Error, info?: ErrorInfo }>

For

Component to optimize the rendering of a list of elements without need to specify a key value for all elements, and other options. See demo

For<T, S extends T>({ of, elementKey, fallback, filter, sort, map, children }: { of: Array<T>, elementKey?: (T|S) extends object ? keyof (T|S) | ((item: T|S) => Key) : Key | ((item: T|S) => Key), children: (item: T|S, index: number, key: Key) => ReactNode, fallback?: ReactNode, filter?: Parameters<Array<T>["filter"]>[0], sort?: true | Parameters<Array<T>["sort"]>[0], map?: (...args: Parameters<Parameters<Array<T>["map"]>[0]>) => S }): null|JSX.Element|Array<JSX.Element>

ForMemoized

Memoized version of For component. See demo

ForMemoized = memo(For) as typeof For;

LazyComponent

Component Wrapper to lazy loading a Component. See demo

LazyComponent<T extends { default: ComponentType<unknown> } | { [k: string]: ComponentType<unknown> }>({ factory, componentName, fallback, beforeLoad, afterLoad }: { factory: () => Promise<T>, componentName?: string, fallback?: ReactNode, beforeLoad?: ()=>void, afterLoad?: ()=>void })

Show

Generic component used to conditional render part of the view: it renders children when the when prop is truthy, otherwise the fallback prop, if it is present, or null. See demo

Show<T>({ when, fallback, children }: PropsWithChildren<{ when: T|boolean|undefined|null, fallback?: ReactNode }>)

ShowMemoized

Memoized version of Show component. See demo

ShowMemoized = memo(Show);

SwitchCase

It works like switch-case construct. It useful for when there are more than 2 mutual exclusive conditions. See demo

SwitchCase = { Switch, Case };

SwitchCaseMemoized

Memoized version of SwitchCase component. See demo

SwitchCaseMemoized =

UTILS

alphanumericCompare

Function which, given two strings, the type of comparison to be verified, and optional options, performs the comparison between the two strings and returns a boolean indicating whether the indicated comparison is respected or not. See demo

alphanumericCompare(string1: string, string2: string, compareType?: "<" | ">" | "=" | ">=" | "<=", opts?: Intl.CollatorOptions)

changeStringCase

Function that given a string, a case type, and an optional delimiter, returns the string in the specified case or empty string. See demo

changeStringCase({string, caseType, delimiter}:{ string?: string, caseType: "pascalCase" | "snakeCase" | "kebabCase" | "camelCase", delimiter?: "upperCase" | "lowerCase" | string}): string

defaultSerializer

Function to serialize any type of value. See demo

defaultSerializer<T>(target: T)

detectBrowser

It detects used browser or return "No detection". See demo

detectBrowser(): "chrome" | "firefox" | "safari" | "opera" | "edge" | "No detection"

getBase64

Function to obtain a Base64 from value specified if supported, otherwise throw an Error. See demo

getBase64<T>(target: string | Blob | ArrayBuffer | HTMLCanvasElement | HTMLImageElement | T | T[], options?: ToDataURLOptions | UseBase64ObjectOptions<T>): Promise<string>

getKeyObjectFromValue

Function that given an object and a value, returns the corrispondent key of this value or undefined. See demo

getKeyObjectFromValue<T extends Record<string, unknown>, E extends string|number|symbol = keyof T>(object: T, value?: unknown): E | undefined

getObjectFromDottedString

Function that, given a path, a value and an optional object, returns an object with as many properties as there are in the path, assigning the value passed to the last one specified. See demo

getObjectFromDottedString<T, E extends Record<string, unknown>>(path: string, value: T, object?: E): E

hotKeyHandler

Utility function for onKeyDown and onKeyUp events handler that supports keys combination. See demo

hotKeyHandler(hotKeys: `${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}`, listener: (evt: KeyboardEvent | KeyEvt<HTMLElement>) => void | Promise<void>): (evt: KeyboardEvent | KeyEvt<HTMLElement>) => void

isAsync

It detects if a function is asynchronous. See demo

isAsync<T extends unknown[], E = unknown>(fn: E | Promise<E> | ((...args: T)=> E | Promise<E>)): boolean

isClient

It detects if code is running on client. See demo

isClient(): boolean

isDeepEqual

It returns true if the params are equal in depth. See demo

isDeepEqual(objA: unknown, objB: unknown, map = new WeakMap()):boolean

isMouseEvent

It returns true if the event param is of MouseEvent type. See demo

isMouseEvent(event: SyntheticEvent): boolean

isShallowEqual

It returns true if the params are equal until first level depth. See demo

isShallowEqual(objA: unknown, objB: unknown): boolean

isTouchEvent

It returns true if the event param is of TouchEvent type. See demo

isTouchEvent(event: SyntheticEvent | Event): boolean

lazy

Wrapper around React.lazy that works also with component without default export and with possibility to execute a function before and after component loading. See demo

lazy<T extends ComponentType<unknown>>(load: () => Promise<{ [k:string]: T }>, opts: { componentName?: string, beforeLoad?: () => void, afterLoad?: () => void } = {}): LazyExoticComponent<T>

mergeObjects

Function that, given two objects version, merges them into a single one. Via an optional parameter forceUndefinedValue you can define how undefined values are treated. See demo

mergeObjects<T extends object>(oldObj: T, newObj: RecursivePartial<T>, forceUndefinedValue?: boolean): T

removePropertiesFromArrayObjects

Function that, given an array of objects and a property or an array of properties, return a new array without specified properties. See demo

removePropertiesFromArrayObjects<T, E extends string | number | symbol = keyof T>(array: T[], property: E | E[]): Omit<T, E>[]

uniqueElementsArray

Function that given one or more array of object, returns a single array with unique elements by a specified property, an array of properties or none. See demo

uniqueElementsArray<T extends string | number | boolean | ((...args: unknown[]) => unknown) | bigint | object>(property: keyof T | (keyof T)[] | "none", ...args: (T[])[]): T[]

TYPES

Utility Types

Typescript utility types for specified use cases.

NestedKeyOf

Utility type that constructs a type by picking all properties and nested proprerties from T in form property.nestedProprerty.

type NestedKeyOf<T extends Record<string, unknown>>

ErrorModel

Utility type that constructs an object from T and whose property values are boolean.

type ErrorModel<T extends object>

SelectivePartial

Utility type that works like Partial but allows to specify which properties set to optional.

type SelectivePartial<T extends object, E extends keyof T>

RecursivePartial

Utility type that works like Partial but set nested properties to optional also.

type RecursivePartial<T extends object>

Optional

Utility type that constructs a type that is T or E, if specified otherwise null.

type Optional<T = unknown, E = null>

DependencyListTyped

Utility type that works like DependencyList react type but it can be specified dependencies list element types.

type DependencyListTyped<T = unknown>

Union

Utility type that given an array constructs union type from array elements type.

type Union<T extends unknown[]>

ExtractTail

Utility type that given an array extracts a new array with all elements from array expect first.

type ExtractTail<T extends unknown[]>

ExtractMiddle

Utility type that given an array extracts a new array with all elements from array expect first and last.

type ExtractMiddle<T extends unknown[]>

ExtractHead

Utility type that given an array extracts a new array with all elements from array expect last.

type ExtractHead<T extends unknown[]>

PartialRecord

Utility type that constructs a record with all properties set to optional.

type PartialRecord<K extends keyof any, T>

ArrayMinLength1

Utility type that constructs an array of T with one element at least.

type ArrayMinLength1<T>

LanguageBCP47Tags

Utility type for Language BCP-47 tags.

type LanguageBCP47Tags

TypedArray

Utility type for Typed Arrays.

type TypedArray

ESLint configuration

To validate dependencies of custom hooks like useMemoCompare, configure exhaustive-deps with the additionalHooks option:

{
  	"rules": {
    	// ...
    	"react-hooks/exhaustive-deps": [
			"warn",
            {
				"additionalHooks": "(useMemoCompare|useMemoDeepCompare|useCallbackCompare|useCallbackDeepCompare|useLayoutEffectCompare|useLayoutEffectDeepCompare|useInsertionEffectCompare|useInsertionEffectDeepCompare|useEffectCompare|useEffectDeepCompare|usePromiseSuspensible)"
  		  	}
		]
    	"react-hooks/rules-of-hooks": [
			"of",
            {
				"additionalHooks": "(usePromiseSuspensible)"
  		  	}
		]
	}
}

ToDo

  • Hooks/State

    • useSignal (like useProxyStore)
    • createSignal (like createProxyStore)
    • useProxyStore (proxy based)
    • createProxyStore (proxy based)
  • Hooks/Events

    • useDrag (need polyfill for mobile)
    • useDrop (need polyfill for mobile)
  • Hooks/APIDOM

    • useIndexedDB (refer to api)
    • useIdleDetection (not work yet)
  • Components

    • ImageOpt

License

React-Tools is licensed under a MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages