A comprehensive collection of 75+ React hooks for state and UI management including storage, events, browser APIs, and performance optimizations
npx @tessl/cli install tessl/npm-mantine--hooks@8.2.00
# @mantine/hooks
1
2
@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.
3
4
## Package Information
5
6
- **Package Name**: @mantine/hooks
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @mantine/hooks`
10
- **Peer Dependencies**: React 18.x or 19.x
11
12
## Core Imports
13
14
```typescript
15
import { useToggle, useCounter, useLocalStorage, useClipboard } from "@mantine/hooks";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const { useToggle, useCounter, useLocalStorage, useClipboard } = require("@mantine/hooks");
22
```
23
24
## Basic Usage
25
26
```typescript
27
import { useToggle, useCounter, useLocalStorage, useClickOutside } from "@mantine/hooks";
28
import { useRef } from "react";
29
30
function MyComponent() {
31
// Boolean state management
32
const [opened, toggle] = useToggle();
33
34
// Counter with min/max constraints
35
const [count, { increment, decrement, set, reset }] = useCounter(0, { min: 0, max: 10 });
36
37
// localStorage integration with type safety
38
const [value, setValue] = useLocalStorage({ key: "my-key", defaultValue: "default" });
39
40
// Click outside detection
41
const ref = useRef(null);
42
useClickOutside(() => console.log("clicked outside"), null, [ref.current]);
43
44
return (
45
<div ref={ref}>
46
<button onClick={toggle}>Toggle: {opened ? "Open" : "Closed"}</button>
47
<button onClick={increment}>Count: {count}</button>
48
<input value={value} onChange={(e) => setValue(e.target.value)} />
49
</div>
50
);
51
}
52
```
53
54
## Architecture
55
56
@mantine/hooks is built around several key principles:
57
58
- **Consistent APIs**: All hooks follow similar patterns for state management and event handling
59
- **TypeScript Integration**: Full type safety with generic type preservation and inference
60
- **React Best Practices**: Proper use of React hooks patterns, dependency arrays, and cleanup
61
- **SSR Compatibility**: Safe defaults and effect-based initialization for server-side rendering
62
- **Performance Optimized**: Debouncing, throttling, and memoization built into relevant hooks
63
- **Framework Agnostic**: Works with any React application, not tied to specific UI frameworks
64
65
## Capabilities
66
67
### State Management
68
69
Core state management hooks for handling boolean states, counters, lists, objects, and complex state patterns with built-in handlers and type safety.
70
71
```typescript { .api }
72
function useToggle<T = boolean>(options?: readonly T[]): [T, (value?: React.SetStateAction<T>) => void];
73
74
function useCounter(initialValue?: number, options?: { min?: number; max?: number }): [
75
number,
76
{
77
increment: () => void;
78
decrement: () => void;
79
set: (value: number) => void;
80
reset: () => void;
81
}
82
];
83
84
function useDisclosure(initialState?: boolean, options?: {
85
onOpen?: () => void;
86
onClose?: () => void;
87
}): [
88
boolean,
89
{
90
open: () => void;
91
close: () => void;
92
toggle: () => void;
93
}
94
];
95
96
function useListState<T>(initialValue?: T[] | (() => T[])): [
97
T[],
98
{
99
setState: React.Dispatch<React.SetStateAction<T[]>>;
100
append: (...items: T[]) => void;
101
prepend: (...items: T[]) => void;
102
insert: (index: number, ...items: T[]) => void;
103
pop: () => void;
104
shift: () => void;
105
apply: (fn: (item: T, index?: number) => T) => void;
106
remove: (...indices: number[]) => void;
107
reorder: ({ from, to }: { from: number; to: number }) => void;
108
setItem: (index: number, item: T) => void;
109
filter: (fn: (item: T, i: number) => boolean) => void;
110
}
111
];
112
```
113
114
[State Management](./state-management.md)
115
116
### Storage & Persistence
117
118
localStorage and sessionStorage integration with serialization, synchronization across tabs, and SSR support for persistent application state.
119
120
```typescript { .api }
121
function useLocalStorage<T = string>(props: {
122
key: string;
123
defaultValue?: T;
124
getInitialValueInEffect?: boolean;
125
sync?: boolean;
126
serialize?: (value: T) => string;
127
deserialize?: (value: string | undefined) => T;
128
}): [T, (val: T | ((prevState: T) => T)) => void, () => void];
129
130
function readLocalStorageValue<T>(props: {
131
key: string;
132
defaultValue?: T;
133
deserialize?: (value: string | undefined) => T;
134
}): T;
135
136
function useSessionStorage<T = string>(props: {
137
key: string;
138
defaultValue?: T;
139
getInitialValueInEffect?: boolean;
140
sync?: boolean;
141
serialize?: (value: T) => string;
142
deserialize?: (value: string | undefined) => T;
143
}): [T, (val: T | ((prevState: T) => T)) => void, () => void];
144
```
145
146
[Storage](./storage.md)
147
148
### DOM Events & Interactions
149
150
Event handling hooks for click detection, keyboard shortcuts, mouse interactions, hover states, focus management, and touch gestures.
151
152
```typescript { .api }
153
function useClickOutside<T extends HTMLElement = any>(
154
handler: () => void,
155
events?: string[] | null,
156
nodes?: HTMLElement[]
157
): React.RefCallback<T | null>;
158
159
function useHotkeys(
160
hotkeys: [string, (event: KeyboardEvent) => void, { preventDefault?: boolean }?][],
161
tagsToIgnore?: string[],
162
triggerOnContentEditable?: boolean
163
): void;
164
165
function useHover<T extends HTMLElement = any>(): {
166
hovered: boolean;
167
ref: React.RefCallback<T | null>;
168
};
169
170
function useMove<T extends HTMLElement = any>(
171
onChange: (value: { x: number; y: number }) => void,
172
handlers?: {
173
onScrubStart?: () => void;
174
onScrubEnd?: () => void;
175
},
176
dir?: 'ltr' | 'rtl'
177
): {
178
ref: React.RefCallback<T | null>;
179
active: boolean;
180
};
181
```
182
183
[DOM Events](./dom-events.md)
184
185
### Browser APIs
186
187
Integration with browser APIs including clipboard, media queries, fullscreen, viewport, scroll, color scheme detection, and document management.
188
189
```typescript { .api }
190
function useClipboard(options?: { timeout?: number }): {
191
copy: (value: any) => void;
192
reset: () => void;
193
error: Error | null;
194
copied: boolean;
195
};
196
197
function useMediaQuery(
198
query: string,
199
initialValue?: boolean,
200
options?: { getInitialValueInEffect: boolean }
201
): boolean;
202
203
function useViewportSize(): { height: number; width: number };
204
205
function useFullscreen<T extends HTMLElement = any>(): {
206
ref: React.RefCallback<T | null>;
207
toggle: () => Promise<void>;
208
enter: () => Promise<void>;
209
exit: () => Promise<void>;
210
fullscreen: boolean;
211
};
212
213
function useColorScheme(defaultValue?: 'dark' | 'light'): 'dark' | 'light';
214
```
215
216
[Browser APIs](./browser-apis.md)
217
218
### Observers & Detection
219
220
Observer-based hooks for intersection detection, resize monitoring, mutation tracking, and viewport visibility using modern browser Observer APIs.
221
222
```typescript { .api }
223
function useIntersection<T extends HTMLElement = any>(
224
options?: IntersectionObserverInit
225
): {
226
ref: React.RefCallback<T | null>;
227
entry: IntersectionObserverEntry | null;
228
};
229
230
function useResizeObserver<T extends HTMLElement = any>(
231
callback: (entries: ResizeObserverEntry[], observer: ResizeObserver) => void
232
): React.RefCallback<T | null>;
233
234
function useElementSize<T extends HTMLElement = any>(): {
235
ref: React.RefCallback<T | null>;
236
width: number;
237
height: number;
238
};
239
```
240
241
[Observers](./observers.md)
242
243
### Network & Data
244
245
HTTP requests and network status monitoring with loading states, error handling, and connection information.
246
247
```typescript { .api }
248
function useFetch<T>(url: string, options?: RequestInit & { autoInvoke?: boolean }): {
249
data: T | null;
250
loading: boolean;
251
error: Error | null;
252
refetch: () => Promise<any>;
253
abort: () => void;
254
};
255
256
function useNetwork(): {
257
online: boolean;
258
downlink?: number;
259
downlinkMax?: number;
260
effectiveType?: string;
261
rtt?: number;
262
saveData?: boolean;
263
type?: string;
264
};
265
```
266
267
[Network](./network.md)
268
269
### Timing & Performance
270
271
Performance optimization hooks including debouncing, throttling, intervals, timeouts, and callback optimization for efficient React applications.
272
273
```typescript { .api }
274
function useInterval(fn: () => void, interval: number, options?: { autoInvoke?: boolean }): {
275
start: () => void;
276
stop: () => void;
277
toggle: () => void;
278
active: boolean;
279
};
280
281
function useDebouncedCallback<T extends (...args: any[]) => any>(
282
callback: T,
283
delay: number,
284
options?: {
285
maxWait?: number;
286
leading?: boolean;
287
trailing?: boolean;
288
}
289
): T & {
290
cancel: () => void;
291
flush: () => void;
292
pending: () => boolean;
293
};
294
295
function useDebouncedState<T>(defaultValue: T, wait: number, options?: { leading?: boolean }): [
296
T,
297
React.Dispatch<React.SetStateAction<T>>
298
];
299
```
300
301
[Timing](./timing.md)
302
303
### Navigation & Scroll
304
305
Navigation helpers and scroll management including pagination logic, smooth scrolling, scroll spy functionality, and headroom patterns.
306
307
```typescript { .api }
308
function usePagination(options: {
309
initialPage?: number;
310
page?: number;
311
total: number;
312
siblings?: number;
313
boundaries?: number;
314
onChange?: (page: number) => void;
315
}): {
316
range: (number | 'dots')[];
317
active: number;
318
setPage: (page: number) => void;
319
next: () => void;
320
previous: () => void;
321
first: () => void;
322
last: () => void;
323
};
324
325
function useScrollIntoView<T extends HTMLElement = any>(options?: {
326
duration?: number;
327
axis?: 'x' | 'y';
328
easing?: (t: number) => number;
329
offset?: number;
330
cancelable?: boolean;
331
onScrollFinish?: () => void;
332
}): {
333
scrollableRef: React.RefCallback<T | null>;
334
targetRef: React.RefCallback<HTMLElement | null>;
335
scrollIntoView: (alignment?: ScrollLogicalPosition) => void;
336
cancel: () => void;
337
};
338
```
339
340
[Navigation](./navigation.md)
341
342
### Device & Environment
343
344
Device and environment detection including operating system, orientation, motion preferences, and user activity monitoring.
345
346
```typescript { .api }
347
function useOs(options?: { getValueInEffect?: boolean }):
348
'undetermined' | 'macos' | 'ios' | 'windows' | 'android' | 'linux';
349
350
function useOrientation(options?: {
351
angle?: number;
352
type?: OrientationType;
353
}): {
354
angle: number;
355
type: OrientationType;
356
};
357
358
function useReducedMotion(initialValue?: boolean, options?: { getInitialValueInEffect?: boolean }): boolean;
359
360
function useIdle(timeout: number, options?: {
361
events?: string[];
362
initialState?: boolean;
363
}): boolean;
364
```
365
366
[Device](./device.md)
367
368
### Lifecycle & Utilities
369
370
React lifecycle utilities and helper hooks for component lifecycle management, ref handling, and common utility patterns.
371
372
```typescript { .api }
373
function useForceUpdate(): () => void;
374
375
function useId(staticId?: string): string;
376
377
function useMounted(): boolean;
378
379
function usePrevious<T>(value: T): T | undefined;
380
381
function useMergedRef<T>(...refs: React.Ref<T>[]): React.RefCallback<T | null>;
382
383
function useDidUpdate(fn: React.EffectCallback, dependencies?: React.DependencyList): void;
384
```
385
386
[Utilities](./utilities.md)
387
388
### Specialized
389
390
Advanced and specialized hooks for unique UI patterns including color picker integration, file dialogs, selection management, and radial interactions.
391
392
```typescript { .api }
393
function useEyeDropper(): {
394
supported: boolean;
395
open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }>;
396
};
397
398
function useFileDialog(options: {
399
multiple?: boolean;
400
accept?: string;
401
capture?: boolean | 'user' | 'environment';
402
onFiles: (files: FileList | null) => void;
403
}): {
404
open: () => void;
405
reset: () => void;
406
};
407
408
function useSelection<T>(
409
items: T[],
410
input?: {
411
multiple?: boolean;
412
value?: T | T[];
413
onSelectionChange?: (value: T | T[]) => void;
414
}
415
): {
416
selected: T[];
417
handlers: {
418
select: (item: T) => void;
419
deselect: (item: T) => void;
420
toggle: (item: T) => void;
421
selectAll: () => void;
422
deselectAll: () => void;
423
setSelection: (items: T[]) => void;
424
};
425
isSelected: (item: T) => boolean;
426
};
427
```
428
429
[Specialized](./specialized.md)
430
431
## Utility Functions
432
433
Core utility functions for common operations used throughout the hook implementations.
434
435
```typescript { .api }
436
function clamp(value: number, min: number, max: number): number;
437
function randomId(): string;
438
function range(start: number, end: number): number[];
439
function shallowEqual(a: any, b: any): boolean;
440
function upperFirst(string: string): string;
441
function lowerFirst(string: string): string;
442
```