0
# Utility Functions
1
2
Helper utilities for data manipulation, caching, type checking, common programming patterns, and component lifecycle management.
3
4
## Capabilities
5
6
### Function Utilities
7
8
#### useMemoize
9
10
Cache function results based on arguments to improve performance.
11
12
```typescript { .api }
13
/**
14
* Cache function results based on arguments
15
* @param resolver - Function to memoize
16
* @param options - Configuration options
17
* @returns Memoized function
18
*/
19
function useMemoize<Args extends any[], Return>(
20
resolver: (...args: Args) => Return,
21
options?: UseMemoizeOptions<Args, Return>
22
): (...args: Args) => Return;
23
24
interface UseMemoizeOptions<Args extends any[], Return> {
25
getKey?: (...args: Args) => string | number;
26
cache?: UseMemoizeCache<string | number, Return>;
27
}
28
29
interface UseMemoizeCache<Key, Value> {
30
has: (key: Key) => boolean;
31
get: (key: Key) => Value | undefined;
32
set: (key: Key, value: Value) => void;
33
delete: (key: Key) => boolean;
34
clear: () => void;
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { useMemoize } from "@vueuse/core";
42
43
// Expensive calculation
44
const fibonacci = useMemoize((n: number): number => {
45
if (n <= 1) return n;
46
return fibonacci(n - 1) + fibonacci(n - 2);
47
});
48
49
// API calls with caching
50
const fetchUser = useMemoize(async (id: string) => {
51
const response = await fetch(`/api/users/${id}`);
52
return response.json();
53
});
54
55
// Custom cache key
56
const cachedFn = useMemoize(
57
(a: number, b: string) => `${a}-${b}`,
58
{
59
getKey: (a, b) => `${a}:${b}`
60
}
61
);
62
```
63
64
#### createUnrefFn
65
66
Create a function that accepts refs and returns unreffed values.
67
68
```typescript { .api }
69
/**
70
* Create function that accepts refs and returns unreffed values
71
* @param fn - Function to wrap
72
* @returns Function that auto-unrefs arguments
73
*/
74
function createUnrefFn<T extends Function>(fn: T): T;
75
```
76
77
### Feature Detection
78
79
#### useSupported
80
81
Check if a browser feature is supported.
82
83
```typescript { .api }
84
/**
85
* Check if a browser feature is supported
86
* @param callback - Feature detection callback
87
* @param sync - Run synchronously
88
* @returns Reactive support state
89
*/
90
function useSupported(
91
callback: () => unknown,
92
sync?: boolean
93
): ComputedRef<boolean>;
94
```
95
96
**Usage Examples:**
97
98
```typescript
99
import { useSupported } from "@vueuse/core";
100
101
// Check for specific APIs
102
const isSupported = useSupported(() => navigator.geolocation);
103
const hasWebGL = useSupported(() => {
104
const canvas = document.createElement('canvas');
105
return canvas.getContext('webgl');
106
});
107
108
// Use in components
109
if (isSupported.value) {
110
// Use the feature
111
}
112
```
113
114
### Data Manipulation
115
116
#### useCloned
117
118
Reactive clone of a ref with various cloning strategies.
119
120
```typescript { .api }
121
/**
122
* Reactive clone of a ref
123
* @param source - Source ref to clone
124
* @param options - Configuration options
125
* @returns Cloned value utilities
126
*/
127
function useCloned<T>(
128
source: MaybeRefOrGetter<T>,
129
options?: UseClonedOptions<T>
130
): UseClonedReturn<T>;
131
132
interface UseClonedReturn<T> {
133
cloned: ComputedRef<T>;
134
sync: () => void;
135
}
136
137
interface UseClonedOptions<T> {
138
manual?: boolean;
139
clone?: CloneFn<T> | boolean;
140
}
141
142
type CloneFn<T> = (source: T) => T;
143
```
144
145
#### useSorted
146
147
Reactive array sorting with custom comparison functions.
148
149
```typescript { .api }
150
/**
151
* Reactive array sorting
152
* @param source - Source array or ref
153
* @param compareFn - Comparison function or options
154
* @param options - Configuration options when compareFn is provided
155
* @returns Sorted array ref
156
*/
157
function useSorted<T>(
158
source: MaybeRefOrGetter<T[]>,
159
compareFn?: (a: T, b: T) => number,
160
options?: UseSortedOptions<T>
161
): ComputedRef<T[]>;
162
163
function useSorted<T>(
164
source: MaybeRefOrGetter<T[]>,
165
options?: UseSortedOptions<T>
166
): ComputedRef<T[]>;
167
168
interface UseSortedOptions<T> {
169
dirty?: Ref<boolean>;
170
compareFn?: (a: T, b: T) => number;
171
}
172
```
173
174
#### useCycleList
175
176
Cycle through a list of items with navigation methods.
177
178
```typescript { .api }
179
/**
180
* Cycle through a list of items
181
* @param list - List of items to cycle through
182
* @param options - Configuration options
183
* @returns Cycle utilities
184
*/
185
function useCycleList<T>(
186
list: MaybeRef<T[]>,
187
options?: UseCycleListOptions<T>
188
): UseCycleListReturn<T>;
189
190
interface UseCycleListReturn<T> {
191
state: Ref<T>;
192
index: Ref<number>;
193
next: (n?: number) => T;
194
prev: (n?: number) => T;
195
go: (i: number) => T;
196
}
197
198
interface UseCycleListOptions<T> {
199
initialValue?: MaybeRef<T>;
200
fallbackIndex?: number;
201
getIndexOf?: (value: T, list: T[]) => number;
202
}
203
```
204
205
### Previous Values
206
207
#### usePrevious
208
209
Get the previous value of a ref.
210
211
```typescript { .api }
212
/**
213
* Get the previous value of a ref
214
* @param value - Source ref
215
* @param initialValue - Initial previous value
216
* @returns Previous value ref
217
*/
218
function usePrevious<T>(
219
value: MaybeRef<T>,
220
initialValue?: T
221
): Readonly<Ref<T | undefined>>;
222
```
223
224
### Encoding & Decoding
225
226
#### useBase64
227
228
Reactive Base64 encoding and decoding.
229
230
```typescript { .api }
231
/**
232
* Reactive Base64 encoding and decoding
233
* @param text - Text to encode/decode
234
* @param options - Configuration options
235
* @returns Base64 utilities
236
*/
237
function useBase64(
238
text: MaybeRefOrGetter<string>,
239
options?: UseBase64Options
240
): UseBase64Return;
241
242
interface UseBase64Return {
243
base64: ComputedRef<string>;
244
buffer: ComputedRef<ArrayBuffer>;
245
promise: ComputedRef<Promise<string>>;
246
}
247
248
interface UseBase64Options {
249
serializer?: UseBase64Serializer;
250
}
251
252
interface UseBase64Serializer {
253
read: (text: string) => string;
254
write: (text: string) => string;
255
}
256
```
257
258
### Text Utilities
259
260
#### useTextDirection
261
262
Reactive text direction tracking and management.
263
264
```typescript { .api }
265
/**
266
* Reactive text direction
267
* @param options - Configuration options
268
* @returns Text direction utilities
269
*/
270
function useTextDirection(options?: UseTextDirectionOptions): UseTextDirectionReturn;
271
272
interface UseTextDirectionReturn {
273
dir: WritableComputedRef<UseTextDirectionValue>;
274
}
275
276
interface UseTextDirectionOptions extends ConfigurableDocument {
277
selector?: string;
278
observe?: boolean;
279
initialValue?: UseTextDirectionValue;
280
}
281
282
type UseTextDirectionValue = 'ltr' | 'rtl' | 'auto';
283
```
284
285
#### useTextSelection
286
287
Reactive text selection information.
288
289
```typescript { .api }
290
/**
291
* Reactive text selection
292
* @param options - Configuration options
293
* @returns Text selection state
294
*/
295
function useTextSelection(options?: UseTextSelectionOptions): UseTextSelectionReturn;
296
297
interface UseTextSelectionReturn {
298
text: ComputedRef<string>;
299
rects: ComputedRef<DOMRect[]>;
300
ranges: ComputedRef<Range[]>;
301
selection: ComputedRef<Selection | null>;
302
}
303
```
304
305
#### useTextareaAutosize
306
307
Auto-resize textarea based on content.
308
309
```typescript { .api }
310
/**
311
* Auto-resize textarea based on content
312
* @param element - Textarea element or ref
313
* @param input - Input value (reactive)
314
* @param options - Configuration options
315
* @returns Textarea utilities
316
*/
317
function useTextareaAutosize(
318
element?: MaybeElementRef<HTMLTextAreaElement>,
319
input?: MaybeRef<string>,
320
options?: UseTextareaAutosizeOptions
321
): UseTextareaAutosizeReturn;
322
323
interface UseTextareaAutosizeReturn {
324
textarea: Ref<HTMLTextAreaElement | undefined>;
325
input: Ref<string>;
326
triggerResize: () => void;
327
}
328
329
interface UseTextareaAutosizeOptions {
330
watch?: MaybeElementRef | MaybeElementRef[];
331
onResize?: () => void;
332
styleProp?: string;
333
}
334
```
335
336
### Image Utilities
337
338
#### useImage
339
340
Reactive image loading with status tracking.
341
342
```typescript { .api }
343
/**
344
* Reactive image loading with status tracking
345
* @param options - Configuration options
346
* @returns Image loading state and utilities
347
*/
348
function useImage(options: UseImageOptions): UseImageReturn;
349
350
interface UseImageReturn {
351
isLoading: Ref<boolean>;
352
error: Ref<Event | null>;
353
execute: (options?: UseImageOptions) => Promise<HTMLImageElement>;
354
}
355
356
interface UseImageOptions {
357
src: string;
358
srcset?: string;
359
sizes?: string;
360
class?: string;
361
loading?: 'eager' | 'lazy';
362
crossorigin?: 'anonymous' | 'use-credentials' | '';
363
referrerPolicy?: 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
364
}
365
```
366
367
### Object URL Management
368
369
#### useObjectUrl
370
371
Create and manage object URLs for Blob/File objects.
372
373
```typescript { .api }
374
/**
375
* Create and manage object URLs for Blob/File objects
376
* @param object - Blob, File, or MediaSource object
377
* @returns Object URL utilities
378
*/
379
function useObjectUrl(object: MaybeRef<Blob | MediaSource | undefined>): ComputedRef<string | undefined>;
380
```
381
382
### Time Utilities
383
384
#### useNow
385
386
Reactive current timestamp with configurable update intervals.
387
388
```typescript { .api }
389
/**
390
* Reactive current timestamp
391
* @param options - Configuration options
392
* @returns Current timestamp ref
393
*/
394
function useNow(options?: UseNowOptions): Ref<Date>;
395
396
interface UseNowOptions<Controls extends boolean = false> {
397
controls?: Controls;
398
interval?: 'requestAnimationFrame' | number;
399
}
400
```
401
402
#### useTimestamp
403
404
Reactive timestamp with millisecond precision.
405
406
```typescript { .api }
407
/**
408
* Reactive timestamp with millisecond precision
409
* @param options - Configuration options
410
* @returns Timestamp utilities
411
*/
412
function useTimestamp(options?: UseTimestampOptions): UseTimestampReturn;
413
414
interface UseTimestampReturn {
415
timestamp: Ref<number>;
416
pause: Fn;
417
resume: Fn;
418
}
419
420
interface UseTimestampOptions<Controls extends boolean = false> {
421
controls?: Controls;
422
offset?: number;
423
immediate?: boolean;
424
interval?: 'requestAnimationFrame' | number;
425
callback?: (timestamp: number) => void;
426
}
427
```
428
429
#### useTimeAgo
430
431
Reactive time ago formatting.
432
433
```typescript { .api }
434
/**
435
* Reactive time ago formatting
436
* @param time - Time to format
437
* @param options - Configuration options
438
* @returns Formatted time ago string
439
*/
440
function useTimeAgo(
441
time: MaybeComputedRef<Date | number | string>,
442
options?: UseTimeAgoOptions<boolean>
443
): ComputedRef<string>;
444
445
interface UseTimeAgoOptions<Controls extends boolean = false> {
446
controls?: Controls;
447
updateInterval?: number;
448
max?: string | number | Date | UseTimeAgoUnit;
449
fullDateFormatter?: (date: Date) => string;
450
messages?: UseTimeAgoMessages;
451
rounding?: number;
452
showSecond?: boolean;
453
unit?: UseTimeAgoUnitNamesDefault;
454
}
455
456
type UseTimeAgoUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
457
```
458
459
#### useTimeoutPoll
460
461
Reactive timeout-based polling.
462
463
```typescript { .api }
464
/**
465
* Reactive timeout-based polling
466
* @param fn - Function to poll
467
* @param interval - Poll interval in milliseconds
468
* @param options - Configuration options
469
* @returns Poll utilities
470
*/
471
function useTimeoutPoll(
472
fn: () => Awaitable<void>,
473
interval: MaybeRef<number>,
474
options?: UseTimeoutPollOptions
475
): UseTimeoutPollReturn;
476
477
interface UseTimeoutPollReturn extends Pausable {
478
isActive: Ref<boolean>;
479
}
480
```
481
482
### Countdown & Timing
483
484
#### useCountdown
485
486
Reactive countdown timer with completion callbacks.
487
488
```typescript { .api }
489
/**
490
* Reactive countdown timer
491
* @param count - Initial count or target date
492
* @param options - Configuration options
493
* @returns Countdown utilities
494
*/
495
function useCountdown(
496
count: MaybeRef<number>,
497
options?: UseCountdownOptions
498
): UseCountdownReturn;
499
500
interface UseCountdownReturn {
501
count: Ref<number>;
502
start: () => void;
503
pause: () => void;
504
resume: () => void;
505
stop: () => void;
506
reset: (newCount?: number) => void;
507
restart: (newCount?: number) => void;
508
isActive: Ref<boolean>;
509
}
510
511
interface UseCountdownOptions {
512
interval?: number;
513
onFinish?: () => void;
514
onUpdate?: (count: number) => void;
515
}
516
```
517
518
### Pagination
519
520
#### useOffsetPagination
521
522
Reactive offset-based pagination utilities.
523
524
```typescript { .api }
525
/**
526
* Reactive offset-based pagination
527
* @param options - Configuration options
528
* @returns Pagination utilities
529
*/
530
function useOffsetPagination(options: UseOffsetPaginationOptions): UseOffsetPaginationReturn;
531
532
interface UseOffsetPaginationReturn {
533
currentPage: Ref<number>;
534
currentPageSize: Ref<number>;
535
pageCount: ComputedRef<number>;
536
isFirstPage: ComputedRef<boolean>;
537
isLastPage: ComputedRef<boolean>;
538
prev: () => void;
539
next: () => void;
540
}
541
542
interface UseOffsetPaginationOptions {
543
total: MaybeRefOrGetter<number>;
544
page?: MaybeRef<number>;
545
pageSize?: MaybeRef<number>;
546
onPageChange?: (returnValue: UseOffsetPaginationReturn) => void;
547
onPageSizeChange?: (returnValue: UseOffsetPaginationReturn) => void;
548
}
549
```