or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

browser-apis.mddevice.mddom-events.mdindex.mdnavigation.mdnetwork.mdobservers.mdspecialized.mdstate-management.mdstorage.mdtiming.mdutilities.md
tile.json

tessl/npm-mantine--hooks

A comprehensive collection of 75+ React hooks for state and UI management including storage, events, browser APIs, and performance optimizations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@mantine/hooks@8.2.x

To install, run

npx @tessl/cli install tessl/npm-mantine--hooks@8.2.0

index.mddocs/

@mantine/hooks

@mantine/hooks is a comprehensive collection of 75+ React hooks designed for state and UI management in React applications. It provides TypeScript-first implementations covering state management, browser APIs, DOM interactions, observers, networking, timing optimizations, and specialized UI patterns. Each hook follows React best practices and offers consistent APIs with full type safety.

Package Information

  • Package Name: @mantine/hooks
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @mantine/hooks
  • Peer Dependencies: React 18.x or 19.x

Core Imports

import { useToggle, useCounter, useLocalStorage, useClipboard } from "@mantine/hooks";

For CommonJS:

const { useToggle, useCounter, useLocalStorage, useClipboard } = require("@mantine/hooks");

Basic Usage

import { useToggle, useCounter, useLocalStorage, useClickOutside } from "@mantine/hooks";
import { useRef } from "react";

function MyComponent() {
  // Boolean state management
  const [opened, toggle] = useToggle();
  
  // Counter with min/max constraints
  const [count, { increment, decrement, set, reset }] = useCounter(0, { min: 0, max: 10 });
  
  // localStorage integration with type safety
  const [value, setValue] = useLocalStorage({ key: "my-key", defaultValue: "default" });
  
  // Click outside detection
  const ref = useRef(null);
  useClickOutside(() => console.log("clicked outside"), null, [ref.current]);
  
  return (
    <div ref={ref}>
      <button onClick={toggle}>Toggle: {opened ? "Open" : "Closed"}</button>
      <button onClick={increment}>Count: {count}</button>
      <input value={value} onChange={(e) => setValue(e.target.value)} />
    </div>
  );
}

Architecture

@mantine/hooks is built around several key principles:

  • Consistent APIs: All hooks follow similar patterns for state management and event handling
  • TypeScript Integration: Full type safety with generic type preservation and inference
  • React Best Practices: Proper use of React hooks patterns, dependency arrays, and cleanup
  • SSR Compatibility: Safe defaults and effect-based initialization for server-side rendering
  • Performance Optimized: Debouncing, throttling, and memoization built into relevant hooks
  • Framework Agnostic: Works with any React application, not tied to specific UI frameworks

Capabilities

State Management

Core state management hooks for handling boolean states, counters, lists, objects, and complex state patterns with built-in handlers and type safety.

function useToggle<T = boolean>(options?: readonly T[]): [T, (value?: React.SetStateAction<T>) => void];

function useCounter(initialValue?: number, options?: { min?: number; max?: number }): [
  number,
  {
    increment: () => void;
    decrement: () => void;
    set: (value: number) => void;
    reset: () => void;
  }
];

function useDisclosure(initialState?: boolean, options?: {
  onOpen?: () => void;
  onClose?: () => void;
}): [
  boolean,
  {
    open: () => void;
    close: () => void;
    toggle: () => void;
  }
];

function useListState<T>(initialValue?: T[] | (() => T[])): [
  T[],
  {
    setState: React.Dispatch<React.SetStateAction<T[]>>;
    append: (...items: T[]) => void;
    prepend: (...items: T[]) => void;
    insert: (index: number, ...items: T[]) => void;
    pop: () => void;
    shift: () => void;
    apply: (fn: (item: T, index?: number) => T) => void;
    remove: (...indices: number[]) => void;
    reorder: ({ from, to }: { from: number; to: number }) => void;
    setItem: (index: number, item: T) => void;
    filter: (fn: (item: T, i: number) => boolean) => void;
  }
];

State Management

Storage & Persistence

localStorage and sessionStorage integration with serialization, synchronization across tabs, and SSR support for persistent application state.

function useLocalStorage<T = string>(props: {
  key: string;
  defaultValue?: T;
  getInitialValueInEffect?: boolean;
  sync?: boolean;
  serialize?: (value: T) => string;
  deserialize?: (value: string | undefined) => T;
}): [T, (val: T | ((prevState: T) => T)) => void, () => void];

function readLocalStorageValue<T>(props: {
  key: string;
  defaultValue?: T;
  deserialize?: (value: string | undefined) => T;
}): T;

function useSessionStorage<T = string>(props: {
  key: string;
  defaultValue?: T;
  getInitialValueInEffect?: boolean;
  sync?: boolean;
  serialize?: (value: T) => string;
  deserialize?: (value: string | undefined) => T;
}): [T, (val: T | ((prevState: T) => T)) => void, () => void];

Storage

DOM Events & Interactions

Event handling hooks for click detection, keyboard shortcuts, mouse interactions, hover states, focus management, and touch gestures.

function useClickOutside<T extends HTMLElement = any>(
  handler: () => void,
  events?: string[] | null,
  nodes?: HTMLElement[]
): React.RefCallback<T | null>;

function useHotkeys(
  hotkeys: [string, (event: KeyboardEvent) => void, { preventDefault?: boolean }?][],
  tagsToIgnore?: string[],
  triggerOnContentEditable?: boolean
): void;

function useHover<T extends HTMLElement = any>(): {
  hovered: boolean;
  ref: React.RefCallback<T | null>;
};

function useMove<T extends HTMLElement = any>(
  onChange: (value: { x: number; y: number }) => void,
  handlers?: {
    onScrubStart?: () => void;
    onScrubEnd?: () => void;
  },
  dir?: 'ltr' | 'rtl'
): {
  ref: React.RefCallback<T | null>;
  active: boolean;
};

DOM Events

Browser APIs

Integration with browser APIs including clipboard, media queries, fullscreen, viewport, scroll, color scheme detection, and document management.

function useClipboard(options?: { timeout?: number }): {
  copy: (value: any) => void;
  reset: () => void;
  error: Error | null;
  copied: boolean;
};

function useMediaQuery(
  query: string,
  initialValue?: boolean,
  options?: { getInitialValueInEffect: boolean }
): boolean;

function useViewportSize(): { height: number; width: number };

function useFullscreen<T extends HTMLElement = any>(): {
  ref: React.RefCallback<T | null>;
  toggle: () => Promise<void>;
  enter: () => Promise<void>;
  exit: () => Promise<void>;
  fullscreen: boolean;
};

function useColorScheme(defaultValue?: 'dark' | 'light'): 'dark' | 'light';

Browser APIs

Observers & Detection

Observer-based hooks for intersection detection, resize monitoring, mutation tracking, and viewport visibility using modern browser Observer APIs.

function useIntersection<T extends HTMLElement = any>(
  options?: IntersectionObserverInit
): {
  ref: React.RefCallback<T | null>;
  entry: IntersectionObserverEntry | null;
};

function useResizeObserver<T extends HTMLElement = any>(
  callback: (entries: ResizeObserverEntry[], observer: ResizeObserver) => void
): React.RefCallback<T | null>;

function useElementSize<T extends HTMLElement = any>(): {
  ref: React.RefCallback<T | null>;
  width: number;
  height: number;
};

Observers

Network & Data

HTTP requests and network status monitoring with loading states, error handling, and connection information.

function useFetch<T>(url: string, options?: RequestInit & { autoInvoke?: boolean }): {
  data: T | null;
  loading: boolean;
  error: Error | null;
  refetch: () => Promise<any>;
  abort: () => void;
};

function useNetwork(): {
  online: boolean;
  downlink?: number;
  downlinkMax?: number;
  effectiveType?: string;
  rtt?: number;
  saveData?: boolean;
  type?: string;
};

Network

Timing & Performance

Performance optimization hooks including debouncing, throttling, intervals, timeouts, and callback optimization for efficient React applications.

function useInterval(fn: () => void, interval: number, options?: { autoInvoke?: boolean }): {
  start: () => void;
  stop: () => void;
  toggle: () => void;
  active: boolean;
};

function useDebouncedCallback<T extends (...args: any[]) => any>(
  callback: T,
  delay: number,
  options?: {
    maxWait?: number;
    leading?: boolean;
    trailing?: boolean;
  }
): T & {
  cancel: () => void;
  flush: () => void;
  pending: () => boolean;
};

function useDebouncedState<T>(defaultValue: T, wait: number, options?: { leading?: boolean }): [
  T,
  React.Dispatch<React.SetStateAction<T>>
];

Timing

Navigation & Scroll

Navigation helpers and scroll management including pagination logic, smooth scrolling, scroll spy functionality, and headroom patterns.

function usePagination(options: {
  initialPage?: number;
  page?: number;
  total: number;
  siblings?: number;
  boundaries?: number;
  onChange?: (page: number) => void;
}): {
  range: (number | 'dots')[];
  active: number;
  setPage: (page: number) => void;
  next: () => void;
  previous: () => void;
  first: () => void;
  last: () => void;
};

function useScrollIntoView<T extends HTMLElement = any>(options?: {
  duration?: number;
  axis?: 'x' | 'y';
  easing?: (t: number) => number;
  offset?: number;
  cancelable?: boolean;
  onScrollFinish?: () => void;
}): {
  scrollableRef: React.RefCallback<T | null>;
  targetRef: React.RefCallback<HTMLElement | null>;
  scrollIntoView: (alignment?: ScrollLogicalPosition) => void;
  cancel: () => void;
};

Navigation

Device & Environment

Device and environment detection including operating system, orientation, motion preferences, and user activity monitoring.

function useOs(options?: { getValueInEffect?: boolean }): 
  'undetermined' | 'macos' | 'ios' | 'windows' | 'android' | 'linux';

function useOrientation(options?: {
  angle?: number;
  type?: OrientationType;
}): {
  angle: number;
  type: OrientationType;
};

function useReducedMotion(initialValue?: boolean, options?: { getInitialValueInEffect?: boolean }): boolean;

function useIdle(timeout: number, options?: {
  events?: string[];
  initialState?: boolean;
}): boolean;

Device

Lifecycle & Utilities

React lifecycle utilities and helper hooks for component lifecycle management, ref handling, and common utility patterns.

function useForceUpdate(): () => void;

function useId(staticId?: string): string;

function useMounted(): boolean;

function usePrevious<T>(value: T): T | undefined;

function useMergedRef<T>(...refs: React.Ref<T>[]): React.RefCallback<T | null>;

function useDidUpdate(fn: React.EffectCallback, dependencies?: React.DependencyList): void;

Utilities

Specialized

Advanced and specialized hooks for unique UI patterns including color picker integration, file dialogs, selection management, and radial interactions.

function useEyeDropper(): {
  supported: boolean;
  open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }>;
};

function useFileDialog(options: {
  multiple?: boolean;
  accept?: string;
  capture?: boolean | 'user' | 'environment';
  onFiles: (files: FileList | null) => void;
}): {
  open: () => void;
  reset: () => void;
};

function useSelection<T>(
  items: T[],
  input?: {
    multiple?: boolean;
    value?: T | T[];
    onSelectionChange?: (value: T | T[]) => void;
  }
): {
  selected: T[];
  handlers: {
    select: (item: T) => void;
    deselect: (item: T) => void;
    toggle: (item: T) => void;
    selectAll: () => void;
    deselectAll: () => void;
    setSelection: (items: T[]) => void;
  };
  isSelected: (item: T) => boolean;
};

Specialized

Utility Functions

Core utility functions for common operations used throughout the hook implementations.

function clamp(value: number, min: number, max: number): number;
function randomId(): string;
function range(start: number, end: number): number[];
function shallowEqual(a: any, b: any): boolean;
function upperFirst(string: string): string;
function lowerFirst(string: string): string;