0
# State Management
1
2
Core reactive state utilities for managing component and application state with persistence, history tracking, and v-model integration.
3
4
## Capabilities
5
6
### Storage Management
7
8
#### useStorage
9
10
Reactive LocalStorage/SessionStorage with automatic serialization and type safety.
11
12
```typescript { .api }
13
/**
14
* Reactive storage utility with automatic serialization
15
* @param key - Storage key
16
* @param defaults - Default value
17
* @param storage - Storage instance (localStorage by default)
18
* @param options - Configuration options
19
* @returns Reactive ref with storage sync
20
*/
21
function useStorage<T>(
22
key: string,
23
defaults: MaybeRefOrGetter<T>,
24
storage?: StorageLike,
25
options?: UseStorageOptions<T>
26
): RemovableRef<T>;
27
28
interface UseStorageOptions<T> {
29
flush?: 'pre' | 'post' | 'sync';
30
deep?: boolean;
31
listenToStorageChanges?: boolean;
32
writeDefaults?: boolean;
33
mergeDefaults?: boolean | ((storageValue: T, defaults: T) => T);
34
serializer?: StorageSerializer<T>;
35
onError?: (error: Error) => void;
36
shallow?: boolean;
37
initOnMounted?: boolean;
38
}
39
40
interface RemovableRef<T> extends Ref<T> {
41
/** Remove the storage item and reset to default */
42
remove(): void;
43
}
44
45
interface StorageSerializer<T> {
46
read(value: string): T;
47
write(value: T): string;
48
}
49
```
50
51
**Usage Examples:**
52
53
```typescript
54
import { useStorage } from "@vueuse/core";
55
56
// String storage
57
const name = useStorage('user-name', 'Anonymous');
58
59
// Object storage with automatic JSON serialization
60
const settings = useStorage('app-settings', {
61
theme: 'light',
62
language: 'en'
63
});
64
65
// Array storage
66
const favorites = useStorage('favorites', [] as string[]);
67
68
// Custom serializer for dates
69
const lastLogin = useStorage('last-login', new Date(), undefined, {
70
serializer: {
71
read: (v: string) => new Date(v),
72
write: (v: Date) => v.toISOString()
73
}
74
});
75
76
// Remove storage item
77
settings.remove(); // Resets to default and removes from storage
78
```
79
80
#### useLocalStorage
81
82
Shorthand for `useStorage` with localStorage.
83
84
```typescript { .api }
85
/**
86
* Reactive localStorage wrapper
87
* @param key - Storage key
88
* @param defaults - Default value
89
* @param options - Configuration options
90
* @returns Reactive ref synced with localStorage
91
*/
92
function useLocalStorage<T>(
93
key: string,
94
defaults: MaybeRefOrGetter<T>,
95
options?: UseStorageOptions<T>
96
): RemovableRef<T>;
97
```
98
99
#### useSessionStorage
100
101
Shorthand for `useStorage` with sessionStorage.
102
103
```typescript { .api }
104
/**
105
* Reactive sessionStorage wrapper
106
* @param key - Storage key
107
* @param defaults - Default value
108
* @param options - Configuration options
109
* @returns Reactive ref synced with sessionStorage
110
*/
111
function useSessionStorage<T>(
112
key: string,
113
defaults: MaybeRefOrGetter<T>,
114
options?: UseStorageOptions<T>
115
): RemovableRef<T>;
116
```
117
118
#### useStorageAsync
119
120
Reactive async storage for custom storage backends.
121
122
```typescript { .api }
123
/**
124
* Reactive async storage utility
125
* @param key - Storage key
126
* @param defaults - Default value
127
* @param storage - Async storage instance
128
* @param options - Configuration options
129
* @returns Reactive ref with async storage sync
130
*/
131
function useStorageAsync<T>(
132
key: string,
133
defaults: MaybeRefOrGetter<T>,
134
storage: StorageLikeAsync,
135
options?: UseStorageAsyncOptions<T>
136
): RemovableRef<T>;
137
138
interface StorageLikeAsync {
139
getItem: (key: string) => Awaitable<string | null>;
140
setItem: (key: string, value: string) => Awaitable<void>;
141
removeItem: (key: string) => Awaitable<void>;
142
}
143
```
144
145
### Component State Management
146
147
#### useVModel
148
149
Shorthand for props + emit -> ref pattern in Vue components.
150
151
```typescript { .api }
152
/**
153
* Shorthand for v-model binding in components
154
* @param props - Component props object
155
* @param key - Prop key to bind (defaults to 'modelValue')
156
* @param emit - Component emit function
157
* @param options - Configuration options
158
* @returns Writable computed ref
159
*/
160
function useVModel<P extends object, K extends keyof P>(
161
props: P,
162
key?: K,
163
emit?: (name: string, ...args: any[]) => void,
164
options?: UseVModelOptions<P[K], true>
165
): WritableComputedRef<P[K]>;
166
167
interface UseVModelOptions<T, Passive> {
168
passive?: Passive;
169
eventName?: string;
170
deep?: boolean;
171
defaultValue?: T;
172
clone?: boolean | CloneFn<T>;
173
shouldEmit?: (v: T) => boolean;
174
}
175
```
176
177
**Usage Examples:**
178
179
```typescript
180
import { useVModel } from "@vueuse/core";
181
182
// In a component with v-model
183
export default defineComponent({
184
props: {
185
modelValue: String,
186
count: Number
187
},
188
emits: ['update:modelValue', 'update:count'],
189
setup(props, { emit }) {
190
// Default v-model binding
191
const value = useVModel(props, 'modelValue', emit);
192
193
// Named v-model binding
194
const count = useVModel(props, 'count', emit);
195
196
// Passive mode (no emit, only reactive to prop changes)
197
const readOnly = useVModel(props, 'modelValue', emit, { passive: true });
198
199
return { value, count, readOnly };
200
}
201
});
202
```
203
204
#### useVModels
205
206
Shorthand for multiple v-model bindings.
207
208
```typescript { .api }
209
/**
210
* Multiple v-model bindings shorthand
211
* @param props - Component props object
212
* @param emit - Component emit function
213
* @param options - Configuration options
214
* @returns Object with reactive refs for each prop
215
*/
216
function useVModels<P extends object>(
217
props: P,
218
emit?: (name: string, ...args: any[]) => void,
219
options?: UseVModelsOptions
220
): ToRefs<P>;
221
222
interface UseVModelsOptions {
223
deep?: boolean;
224
passive?: boolean;
225
}
226
```
227
228
### State History
229
230
#### useRefHistory
231
232
Track changes to a ref with undo/redo capabilities.
233
234
```typescript { .api }
235
/**
236
* Track ref value history with undo/redo
237
* @param source - Source ref to track
238
* @param options - Configuration options
239
* @returns History utilities
240
*/
241
function useRefHistory<Raw, Serialized = Raw>(
242
source: Ref<Raw>,
243
options?: UseRefHistoryOptions<Raw, Serialized>
244
): UseRefHistoryReturn<Raw, Serialized>;
245
246
interface UseRefHistoryReturn<Raw, Serialized> {
247
source: Ref<Raw>;
248
history: Ref<UseRefHistoryRecord<Serialized>[]>;
249
last: Ref<UseRefHistoryRecord<Serialized>>;
250
undoStack: Ref<UseRefHistoryRecord<Serialized>[]>;
251
redoStack: Ref<UseRefHistoryRecord<Serialized>[]>;
252
canUndo: Ref<boolean>;
253
canRedo: Ref<boolean>;
254
undo(): void;
255
redo(): void;
256
clear(): void;
257
pause(): void;
258
resume(): void;
259
commit(): void;
260
}
261
262
interface UseRefHistoryRecord<T> {
263
snapshot: T;
264
timestamp: number;
265
}
266
```
267
268
**Usage Examples:**
269
270
```typescript
271
import { ref } from "vue";
272
import { useRefHistory } from "@vueuse/core";
273
274
const counter = ref(0);
275
const { history, undo, redo, canUndo, canRedo } = useRefHistory(counter);
276
277
counter.value = 1;
278
counter.value = 2;
279
counter.value = 3;
280
281
console.log(history.value.length); // 4 (including initial)
282
console.log(canUndo.value); // true
283
284
undo(); // counter.value becomes 2
285
undo(); // counter.value becomes 1
286
287
console.log(canRedo.value); // true
288
redo(); // counter.value becomes 2
289
```
290
291
#### useManualRefHistory
292
293
Manual ref history tracking (no automatic commits).
294
295
```typescript { .api }
296
/**
297
* Manual ref history tracking without automatic commits
298
* @param source - Source ref to track
299
* @param options - Configuration options
300
* @returns History utilities with manual commit
301
*/
302
function useManualRefHistory<Raw, Serialized = Raw>(
303
source: Ref<Raw>,
304
options?: UseManualRefHistoryOptions<Raw, Serialized>
305
): UseManualRefHistoryReturn<Raw, Serialized>;
306
```
307
308
#### useDebouncedRefHistory
309
310
Debounced ref history tracking.
311
312
```typescript { .api }
313
/**
314
* Debounced ref history tracking
315
* @param source - Source ref to track
316
* @param options - Configuration options including debounce timing
317
* @returns History utilities with debounced commits
318
*/
319
function useDebouncedRefHistory<Raw, Serialized = Raw>(
320
source: Ref<Raw>,
321
options?: UseDebouncedRefHistoryOptions<Raw, Serialized>
322
): UseRefHistoryReturn<Raw, Serialized>;
323
324
interface UseDebouncedRefHistoryOptions<Raw, Serialized> extends UseRefHistoryOptions<Raw, Serialized> {
325
debounce?: number;
326
}
327
```
328
329
#### useThrottledRefHistory
330
331
Throttled ref history tracking.
332
333
```typescript { .api }
334
/**
335
* Throttled ref history tracking
336
* @param source - Source ref to track
337
* @param options - Configuration options including throttle timing
338
* @returns History utilities with throttled commits
339
*/
340
function useThrottledRefHistory<Raw, Serialized = Raw>(
341
source: Ref<Raw>,
342
options?: UseThrottledRefHistoryOptions<Raw, Serialized>
343
): UseRefHistoryReturn<Raw, Serialized>;
344
345
interface UseThrottledRefHistoryOptions<Raw, Serialized> extends UseRefHistoryOptions<Raw, Serialized> {
346
throttle?: number;
347
}
348
```
349
350
### Async State
351
352
#### useAsyncState
353
354
Reactive async state management with loading states.
355
356
```typescript { .api }
357
/**
358
* Reactive async state management
359
* @param promise - Promise or function returning promise
360
* @param initialState - Initial state value
361
* @param options - Configuration options
362
* @returns Async state utilities
363
*/
364
function useAsyncState<Data, Params extends any[] = [], Shallow extends boolean = true>(
365
promise: Promise<Data> | ((...args: Params) => Promise<Data>),
366
initialState: MaybeRef<Data>,
367
options?: UseAsyncStateOptions<Shallow, Data>
368
): UseAsyncStateReturn<Data, Params, Shallow>;
369
370
interface UseAsyncStateReturn<Data, Params extends any[], Shallow extends boolean> {
371
state: ShallowUnwrapRef<Ref<Data>>;
372
isReady: Ref<boolean>;
373
isLoading: Ref<boolean>;
374
error: Ref<unknown>;
375
execute: (...args: Params) => Promise<Data>;
376
executeImmediate: (...args: Params) => Promise<Data>;
377
}
378
```
379
380
**Usage Examples:**
381
382
```typescript
383
import { useAsyncState } from "@vueuse/core";
384
385
// With promise
386
const { state, isReady, isLoading, error } = useAsyncState(
387
fetch('/api/user').then(r => r.json()),
388
{}
389
);
390
391
// With function
392
const { state, execute, isLoading } = useAsyncState(
393
async (id: string) => {
394
const response = await fetch(`/api/user/${id}`);
395
return response.json();
396
},
397
null,
398
{ immediate: false }
399
);
400
401
// Execute manually
402
await execute('123');
403
```
404
405
### Computed Utilities
406
407
#### computedAsync
408
409
Create an asynchronous computed dependency.
410
411
```typescript { .api }
412
/**
413
* Create an asynchronous computed dependency
414
* @param evaluationCallback - Async evaluation function
415
* @param initialState - Initial state
416
* @param options - Configuration options
417
* @returns Async computed ref
418
*/
419
function computedAsync<T>(
420
evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,
421
initialState?: T,
422
options?: AsyncComputedOptions
423
): ComputedRef<T> | Ref<T>;
424
425
interface AsyncComputedOptions {
426
lazy?: boolean;
427
evaluating?: Ref<boolean>;
428
shallow?: boolean;
429
flush?: 'pre' | 'post' | 'sync';
430
onError?: (error: unknown) => void;
431
}
432
433
type AsyncComputedOnCancel = (fn: () => void) => void;
434
```
435
436
#### computedInject
437
438
Combine computed and inject functionality.
439
440
```typescript { .api }
441
/**
442
* Combine computed and inject
443
* @param key - Injection key
444
* @param fn - Computed function
445
* @param defaultSource - Default value source
446
* @param treatDefaultAsFactory - Treat default as factory function
447
* @returns Computed ref with injected dependency
448
*/
449
function computedInject<T, K>(
450
key: InjectionKey<T> | string,
451
fn: (source: T) => K,
452
defaultSource?: T | (() => T),
453
treatDefaultAsFactory?: boolean
454
): ComputedRef<K>;
455
```