0
# State Management
1
2
Comprehensive state management hooks for handling boolean states, counters, lists, objects, and complex state patterns with built-in handlers and type safety.
3
4
## Capabilities
5
6
### useToggle
7
8
Toggle between boolean values or custom array of values with type safety.
9
10
```typescript { .api }
11
/**
12
* Toggle between boolean values or custom array of values
13
* @param options - Array of values to toggle between (default: [false, true])
14
* @returns Tuple of current value and toggle function
15
*/
16
function useToggle<T = boolean>(options?: readonly T[]): UseToggleReturnValue<T>;
17
18
type UseToggleAction<T> = (value?: React.SetStateAction<T>) => void;
19
type UseToggleReturnValue<T> = [T, UseToggleAction<T>];
20
```
21
22
**Usage Examples:**
23
24
```typescript
25
import { useToggle } from "@mantine/hooks";
26
27
// Boolean toggle
28
const [opened, toggle] = useToggle();
29
// toggle() switches between false/true
30
// toggle(true) sets to true
31
32
// Custom values toggle
33
const [theme, toggleTheme] = useToggle(['light', 'dark'] as const);
34
// toggleTheme() switches between 'light' and 'dark'
35
// toggleTheme('dark') sets to 'dark'
36
```
37
38
### useCounter
39
40
Counter with increment/decrement handlers and optional min/max constraints.
41
42
```typescript { .api }
43
/**
44
* Counter with increment/decrement handlers and optional constraints
45
* @param initialValue - Initial counter value (default: 0)
46
* @param options - Configuration with min/max constraints
47
* @returns Tuple of current count and handler object
48
*/
49
function useCounter(initialValue?: number, options?: UseCounterOptions): UseCounterReturnValue;
50
51
interface UseCounterOptions {
52
min?: number;
53
max?: number;
54
}
55
56
interface UseCounterHandlers {
57
increment: () => void;
58
decrement: () => void;
59
set: (value: number) => void;
60
reset: () => void;
61
}
62
63
type UseCounterReturnValue = [number, UseCounterHandlers];
64
```
65
66
**Usage Examples:**
67
68
```typescript
69
import { useCounter } from "@mantine/hooks";
70
71
// Basic counter
72
const [count, { increment, decrement, set, reset }] = useCounter(0);
73
74
// Counter with constraints
75
const [score, handlers] = useCounter(0, { min: 0, max: 100 });
76
// increment() won't go above 100
77
// decrement() won't go below 0
78
```
79
80
### useDisclosure
81
82
Boolean state with open/close/toggle handlers and lifecycle callbacks.
83
84
```typescript { .api }
85
/**
86
* Boolean state with open/close/toggle handlers and callbacks
87
* @param initialState - Initial state (default: false)
88
* @param options - Lifecycle callbacks
89
* @returns Tuple of current state and handler object
90
*/
91
function useDisclosure(initialState?: boolean, options?: UseDisclosureOptions): UseDisclosureReturnValue;
92
93
interface UseDisclosureOptions {
94
onOpen?: () => void;
95
onClose?: () => void;
96
}
97
98
interface UseDisclosureHandlers {
99
open: () => void;
100
close: () => void;
101
toggle: () => void;
102
}
103
104
type UseDisclosureReturnValue = [boolean, UseDisclosureHandlers];
105
```
106
107
**Usage Examples:**
108
109
```typescript
110
import { useDisclosure } from "@mantine/hooks";
111
112
// Modal state management
113
const [opened, { open, close, toggle }] = useDisclosure(false, {
114
onOpen: () => console.log('Modal opened'),
115
onClose: () => console.log('Modal closed'),
116
});
117
118
// Usage in component
119
<Modal opened={opened} onClose={close}>
120
Content
121
</Modal>
122
```
123
124
### useListState
125
126
Array state with comprehensive manipulation handlers including append, insert, remove, reorder operations.
127
128
```typescript { .api }
129
/**
130
* Array state with comprehensive manipulation handlers
131
* @param initialValue - Initial array value or function returning array
132
* @returns Tuple of current array and handler object
133
*/
134
function useListState<T>(initialValue?: T[] | (() => T[])): UseListStateReturnValue<T>;
135
136
interface UseListStateHandlers<T> {
137
setState: React.Dispatch<React.SetStateAction<T[]>>;
138
append: (...items: T[]) => void;
139
prepend: (...items: T[]) => void;
140
insert: (index: number, ...items: T[]) => void;
141
pop: () => void;
142
shift: () => void;
143
apply: (fn: (item: T, index?: number) => T) => void;
144
applyWhere: (condition: (item: T, index: number) => boolean, fn: (item: T, index?: number) => T) => void;
145
remove: (...indices: number[]) => void;
146
reorder: ({ from, to }: { from: number; to: number }) => void;
147
swap: ({ from, to }: { from: number; to: number }) => void;
148
setItem: (index: number, item: T) => void;
149
setItemProp: <K extends keyof T, U extends T[K]>(index: number, prop: K, value: U) => void;
150
filter: (fn: (item: T, i: number) => boolean) => void;
151
}
152
153
type UseListStateReturnValue<T> = [T[], UseListStateHandlers<T>];
154
```
155
156
**Usage Examples:**
157
158
```typescript
159
import { useListState } from "@mantine/hooks";
160
161
const [todos, handlers] = useListState([
162
{ id: 1, text: 'Learn React', completed: false },
163
{ id: 2, text: 'Build app', completed: false },
164
]);
165
166
// Add new todo
167
handlers.append({ id: 3, text: 'Deploy app', completed: false });
168
169
// Toggle completion
170
handlers.setItemProp(0, 'completed', true);
171
172
// Remove completed todos
173
handlers.filter((todo) => !todo.completed);
174
175
// Reorder todos
176
handlers.reorder({ from: 0, to: 1 });
177
```
178
179
### useUncontrolled
180
181
Manage controlled/uncontrolled component state patterns with support for external state control.
182
183
```typescript { .api }
184
/**
185
* Manage controlled/uncontrolled component state patterns
186
* @param options - Configuration for value management
187
* @returns Tuple of current value, setter, and controlled flag
188
*/
189
function useUncontrolled<T>(options: UseUncontrolledOptions<T>): UseUncontrolledReturnValue<T>;
190
191
interface UseUncontrolledOptions<T> {
192
value?: T;
193
defaultValue?: T;
194
finalValue?: T;
195
onChange?: (value: T, ...payload: any[]) => void;
196
}
197
198
type UseUncontrolledReturnValue<T> = [T, (value: T, ...payload: any[]) => void, boolean];
199
```
200
201
### useSetState
202
203
Object state with partial updates similar to class component setState.
204
205
```typescript { .api }
206
/**
207
* Object state with partial updates like class components
208
* @param initialState - Initial state object
209
* @returns Tuple of current state and setter function
210
*/
211
function useSetState<T extends Record<string, any>>(initialState: T): UseSetStateReturnValue<T>;
212
213
type UseSetStateCallback<T> = (current: T) => Partial<T>;
214
type UseSetStateReturnValue<T> = [T, (statePartial: Partial<T> | UseSetStateCallback<T>) => void];
215
```
216
217
**Usage Examples:**
218
219
```typescript
220
import { useSetState } from "@mantine/hooks";
221
222
const [state, setState] = useSetState({
223
name: '',
224
email: '',
225
age: 0
226
});
227
228
// Partial updates
229
setState({ name: 'John' }); // Only updates name
230
setState((current) => ({ age: current.age + 1 })); // Functional update
231
```
232
233
### useInputState
234
235
Input state handler that accepts both event objects and direct values.
236
237
```typescript { .api }
238
/**
239
* Input state handler for form inputs
240
* @param initialValue - Initial input value
241
* @returns Tuple of current value and change handler
242
*/
243
function useInputState<T>(initialValue: T): UseInputStateReturnValue<T>;
244
245
type UseInputStateReturnValue<T> = [T, (event: React.ChangeEvent<HTMLInputElement> | T) => void];
246
```
247
248
**Usage Examples:**
249
250
```typescript
251
import { useInputState } from "@mantine/hooks";
252
253
const [value, setValue] = useInputState('');
254
255
// Use with input
256
<input value={value} onChange={setValue} />
257
258
// Or set directly
259
setValue('new value');
260
```
261
262
### useValidatedState
263
264
State with validation function and validity tracking.
265
266
```typescript { .api }
267
/**
268
* State with validation function and validity tracking
269
* @param initialValue - Initial value
270
* @param validation - Validation function returning boolean
271
* @returns Tuple of [value, isValid] and setter
272
*/
273
function useValidatedState<T>(initialValue: T, validation: (value: T) => boolean): UseValidatedStateReturnValue<T>;
274
275
type UseValidatedStateValue<T> = [T, boolean];
276
type UseValidatedStateReturnValue<T> = [UseValidatedStateValue<T>, (value: T) => void];
277
```
278
279
### useQueue
280
281
Queue data structure with add/update/clean operations and size limit.
282
283
```typescript { .api }
284
/**
285
* Queue data structure with size limit and operations
286
* @param options - Queue configuration
287
* @returns Queue object with state and operations
288
*/
289
function useQueue<T>(options: UseQueueOptions<T>): UseQueueReturnValue<T>;
290
291
interface UseQueueOptions<T> {
292
initialValues?: T[];
293
limit: number;
294
}
295
296
interface UseQueueReturnValue<T> {
297
queue: T[];
298
state: T[];
299
add: (...items: T[]) => void;
300
update: (fn: (state: T[]) => T[]) => void;
301
cleanQueue: () => void;
302
}
303
```
304
305
### useStateHistory
306
307
State with history tracking and navigation (back/forward/go).
308
309
```typescript { .api }
310
/**
311
* State with history tracking and navigation
312
* @param initialValue - Initial state value
313
* @returns Tuple of history state and navigation handlers
314
*/
315
function useStateHistory<T>(initialValue: T): UseStateHistoryReturnValue<T>;
316
317
interface UseStateHistoryHandlers<T> {
318
set: (value: T) => void;
319
back: () => void;
320
forward: () => void;
321
go: (index: number) => void;
322
}
323
324
interface UseStateHistoryValue<T> {
325
current: T;
326
previous: T[];
327
next: T[];
328
}
329
330
type UseStateHistoryReturnValue<T> = [UseStateHistoryValue<T>, UseStateHistoryHandlers<T>];
331
```
332
333
### useMap
334
335
Map data structure with reactive set/remove/toggle operations.
336
337
```typescript { .api }
338
/**
339
* Map data structure with reactive operations
340
* @param initialValues - Initial map entries
341
* @returns Enhanced Map with reactive methods
342
*/
343
function useMap<K, V>(initialValues?: Iterable<readonly [K, V]>): Map<K, V> & {
344
set: (key: K, value: V) => void;
345
setAll: (entries: Iterable<readonly [K, V]>) => void;
346
remove: (key: K) => void;
347
toggle: (key: K, value?: V) => void;
348
reset: () => void;
349
};
350
```
351
352
### useSet
353
354
Set data structure with reactive add/remove/toggle operations.
355
356
```typescript { .api }
357
/**
358
* Set data structure with reactive operations
359
* @param initialValues - Initial set values
360
* @returns Enhanced Set with reactive methods
361
*/
362
function useSet<T>(initialValues?: Iterable<T>): Set<T> & {
363
add: (value: T) => void;
364
addAll: (values: Iterable<T>) => void;
365
remove: (value: T) => void;
366
toggle: (value: T) => void;
367
reset: () => void;
368
};
369
```