or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-utilities.mdcommon-utilities.mdcomputed-utilities.mdindex.mdreactivity.mdref-utilities.mdstate-management.mdtime-async.mdutilities.mdwatch-utilities.md

index.mddocs/

0

# @vueuse/shared

1

2

@vueuse/shared is a collection of essential shared Vue Composition API utilities that serve as foundational building blocks for reactive Vue applications. It provides comprehensive state management utilities, reactivity helpers, array manipulation functions, timing utilities, and extensive watch utilities for building modern Vue applications.

3

4

## Package Information

5

6

- **Package Name**: @vueuse/shared

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @vueuse/shared`

10

- **Peer Dependencies**: Vue 3.5.0+

11

12

## Core Imports

13

14

```typescript

15

import {

16

createGlobalState,

17

reactify,

18

syncRef,

19

useCounter,

20

whenever

21

} from "@vueuse/shared";

22

```

23

24

For CommonJS:

25

26

```javascript

27

const {

28

createGlobalState,

29

reactify,

30

syncRef,

31

useCounter,

32

whenever

33

} = require("@vueuse/shared");

34

```

35

36

## Basic Usage

37

38

```typescript

39

import {

40

createGlobalState,

41

syncRef,

42

useCounter,

43

whenever,

44

ref

45

} from "@vueuse/shared";

46

47

// Global state management

48

const useGlobalCounter = createGlobalState(() => ref(0));

49

const counter = useGlobalCounter();

50

51

// Counter utility with controls

52

const { count, inc, dec, set, reset } = useCounter(0);

53

54

// Ref synchronization

55

const source = ref('hello');

56

const target = ref('');

57

syncRef(source, target); // target will sync with source

58

59

// Conditional watching

60

whenever(count, (value) => {

61

console.log(`Counter is now: ${value}`);

62

});

63

```

64

65

## Architecture

66

67

@vueuse/shared is built around several key architectural patterns:

68

69

- **Composable Functions**: Vue 3 Composition API functions that encapsulate reactive logic

70

- **Global State Management**: Utilities for sharing state across component boundaries

71

- **Reactive Programming**: Functions that work seamlessly with Vue's reactivity system

72

- **Type Safety**: Full TypeScript support with comprehensive type definitions

73

- **Tree Shaking**: Modular exports enabling optimal bundle sizes

74

- **Watch Extensions**: Enhanced watching capabilities beyond Vue's built-in watchers

75

76

## Capabilities

77

78

### State Management

79

80

Global and injectable state utilities for sharing reactive state across components and composables.

81

82

```typescript { .api }

83

function createGlobalState<T>(stateFactory: () => T): () => T;

84

function createInjectionState<Args, Return>(

85

composable: (...args: Args) => Return

86

): [

87

useProvidingState: (...args: Args) => Return,

88

useInjectedState: () => Return | undefined

89

];

90

```

91

92

[State Management](./state-management.md)

93

94

### Reactivity Utilities

95

96

Core utilities for working with Vue's reactivity system, including conversion between refs and reactive objects.

97

98

```typescript { .api }

99

function reactify<T>(fn: T, options?: ReactifyOptions<boolean>): ReactifyReturn<T>;

100

function toReactive<T>(objectRef: MaybeRef<T>): T;

101

function syncRef<L, R>(left: Ref<L>, right: Ref<R>, options?: SyncRefOptions): () => void;

102

```

103

104

[Reactivity Utilities](./reactivity.md)

105

106

### Ref Utilities

107

108

Enhanced ref utilities with automatic behaviors like debouncing, throttling, and automatic reset.

109

110

```typescript { .api }

111

function refDebounced<T>(

112

value: Ref<T>,

113

ms?: number,

114

options?: DebounceFilterOptions

115

): Readonly<Ref<T>>;

116

function refAutoReset<T>(defaultValue: T, afterMs?: number): Ref<T>;

117

function extendRef<T, Extend>(

118

ref: Ref<T>,

119

extend: Extend,

120

options?: ExtendRefOptions

121

): ShallowUnwrapRef<Extend> & Ref<T>;

122

```

123

124

[Ref Utilities](./ref-utilities.md)

125

126

### Array Utilities

127

128

Reactive versions of native Array methods that work with Vue's reactivity system.

129

130

```typescript { .api }

131

function useArrayFilter<T>(

132

list: MaybeRefOrGetter<T[]>,

133

fn: (element: T, index: number, array: T[]) => boolean

134

): ComputedRef<T[]>;

135

function useArrayMap<T, U>(

136

list: MaybeRefOrGetter<T[]>,

137

fn: (element: T, index: number, array: T[]) => U

138

): ComputedRef<U[]>;

139

function useArrayReduce<T, U>(

140

list: MaybeRefOrGetter<T[]>,

141

reducer: (previous: U, current: T, index: number, array: T[]) => U,

142

initialValue: MaybeRefOrGetter<U>

143

): ComputedRef<U>;

144

```

145

146

[Array Utilities](./array-utilities.md)

147

148

### Time & Async Utilities

149

150

Utilities for handling timeouts, intervals, debouncing, throttling, and date formatting with reactive controls.

151

152

```typescript { .api }

153

function useTimeout(interval: number, options?: UseTimeoutOptions): UseTimeoutReturn;

154

function useInterval(interval?: number, options?: UseIntervalOptions): UseIntervalReturn;

155

function useDebounceFn<T>(

156

fn: T,

157

ms?: MaybeRefOrGetter<number>,

158

options?: DebounceFilterOptions

159

): DebouncedFn<T>;

160

function useDateFormat(

161

date: MaybeRefOrGetter<DateLike>,

162

formatStr?: MaybeRefOrGetter<string>,

163

options?: UseDateFormatOptions

164

): UseDateFormatReturn;

165

```

166

167

[Time & Async Utilities](./time-async.md)

168

169

### Watch Utilities

170

171

Enhanced watching capabilities including debounced, throttled, pausable, and conditional watchers.

172

173

```typescript { .api }

174

function watchDebounced<T>(

175

source: WatchSource<T>,

176

cb: WatchCallback<T>,

177

options?: WatchDebouncedOptions

178

): WatchStopHandle;

179

function watchPausable<T>(

180

source: WatchSource<T>,

181

cb: WatchCallback<T>,

182

options?: WatchPausableOptions

183

): WatchPausableReturn;

184

function whenever<T>(

185

source: WatchSource<T | false | null | undefined>,

186

cb: WatchCallback<T>,

187

options?: WatchOptions

188

): WatchStopHandle;

189

```

190

191

[Watch Utilities](./watch-utilities.md)

192

193

### Computed Utilities

194

195

Enhanced computed utilities with manual control and eager evaluation options.

196

197

```typescript { .api }

198

function computedEager<T>(fn: () => T): Readonly<Ref<T>>;

199

function computedWithControl<T, S>(

200

source: WatchSource<S> | WatchSource<S>[],

201

fn: () => T

202

): ComputedWithControl<T>;

203

```

204

205

[Computed Utilities](./computed-utilities.md)

206

207

### Common Utilities

208

209

General purpose utilities including counters, toggles, type conversions, and lifecycle helpers.

210

211

```typescript { .api }

212

function useCounter(initialValue?: number, options?: UseCounterOptions): UseCounterReturn;

213

function useToggle(initialValue?: boolean): UseToggleReturn;

214

function get<T>(obj: MaybeRefOrGetter<T>): T;

215

function set<T>(ref: Ref<T> | ((val: T) => void), value: T): void;

216

```

217

218

[Common Utilities](./common-utilities.md)

219

220

### Utilities

221

222

Core utility functions including filters, type checking, promise helpers, and general-purpose functions that support VueUse shared functionality.

223

224

```typescript { .api }

225

function debounceFilter(ms: MaybeRefOrGetter<number>, options?: DebounceFilterOptions): EventFilter;

226

function throttleFilter(ms: MaybeRefOrGetter<number>, trailing?: boolean, leading?: boolean, rejectOnCancel?: boolean): EventFilter;

227

function pausableFilter(extendFilter?: EventFilter): Pausable & { eventFilter: EventFilter };

228

const isClient: boolean;

229

const isWorker: boolean;

230

function isDef<T = any>(val?: T): val is T;

231

function notNullish<T = any>(val?: T | null | undefined): val is T;

232

function promiseTimeout(ms: number, throwOnTimeout?: boolean, reason?: string): Promise<void>;

233

function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;

234

```

235

236

[Utilities](./utilities.md)

237

238

## Core Types

239

240

```typescript { .api }

241

type MaybeRef<T> = T | Ref<T>;

242

type MaybeRefOrGetter<T> = T | Ref<T> | (() => T);

243

type Fn = () => void;

244

type AnyFn = (...args: any[]) => any;

245

246

type RemovableRef<T> = Omit<Ref<T>, 'value'> & {

247

get value(): T;

248

set value(value: T | null | undefined);

249

};

250

251

type ReadonlyRefOrGetter<T> = ComputedRef<T> | (() => T);

252

253

type DeepMaybeRef<T> = T extends Ref<infer V>

254

? MaybeRef<V>

255

: T extends Array<any> | object

256

? { [K in keyof T]: DeepMaybeRef<T[K]> }

257

: MaybeRef<T>;

258

259

type Arrayable<T> = T[] | T;

260

type ElementOf<T> = T extends (infer E)[] ? E : never;

261

type ShallowUnwrapRef<T> = T extends Ref<infer P> ? P : T;

262

type Awaitable<T> = Promise<T> | T;

263

type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never;

264

type Promisify<T> = Promise<Awaited<T>>;

265

type PromisifyFn<T extends AnyFn> = (...args: ArgumentsType<T>) => Promisify<ReturnType<T>>;

266

type TimerHandle = ReturnType<typeof setTimeout> | undefined;

267

268

interface Pausable {

269

readonly isActive: Readonly<ShallowRef<boolean>>;

270

pause: Fn;

271

resume: Fn;

272

}

273

274

interface Stoppable<StartFnArgs extends any[] = any[]> {

275

readonly isPending: Readonly<Ref<boolean>>;

276

stop: Fn;

277

start: (...args: StartFnArgs) => void;

278

}

279

280

interface ConfigurableFlush {

281

flush?: WatchOptions['flush'];

282

}

283

284

interface ConfigurableFlushSync {

285

flush?: WatchOptions['flush'];

286

}

287

288

type MultiWatchSources = (WatchSource<unknown> | object)[];

289

290

type MapSources<T> = {

291

[K in keyof T]: T[K] extends WatchSource<infer V> ? V : never;

292

};

293

294

type MapOldSources<T, Immediate> = {

295

[K in keyof T]: T[K] extends WatchSource<infer V> ? Immediate extends true ? V | undefined : V : never;

296

};

297

298

type Mutable<T> = { -readonly [P in keyof T]: T[P] };

299

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;

300

type IsAny<T> = IfAny<T, true, false>;

301

```