0
# Lifecycle Hooks
1
2
Vue's lifecycle hooks provide a way to execute code at specific stages of a component's lifecycle. These hooks are available in both the Composition API and Options API.
3
4
## Capabilities
5
6
### Mount & Unmount Hooks
7
8
Hooks for component mounting and unmounting phases.
9
10
```typescript { .api }
11
/**
12
* Registers a callback to be called before the component is mounted
13
* @param hook - Callback function to execute
14
*/
15
function onBeforeMount(hook: () => void): void;
16
17
/**
18
* Registers a callback to be called after the component is mounted
19
* @param hook - Callback function to execute
20
*/
21
function onMounted(hook: () => void): void;
22
23
/**
24
* Registers a callback to be called before the component is unmounted
25
* @param hook - Callback function to execute
26
*/
27
function onBeforeUnmount(hook: () => void): void;
28
29
/**
30
* Registers a callback to be called after the component is unmounted
31
* @param hook - Callback function to execute
32
*/
33
function onUnmounted(hook: () => void): void;
34
```
35
36
**Usage Examples:**
37
38
```typescript
39
import { defineComponent, ref, onBeforeMount, onMounted, onBeforeUnmount, onUnmounted } from "@vue/runtime-core";
40
41
const MyComponent = defineComponent({
42
setup() {
43
const data = ref(null);
44
let timer: NodeJS.Timeout;
45
46
onBeforeMount(() => {
47
console.log("Component is about to be mounted");
48
// Good place to prepare data or setup that doesn't require DOM
49
});
50
51
onMounted(() => {
52
console.log("Component has been mounted to DOM");
53
// DOM is available, good for:
54
// - Accessing DOM elements
55
// - Setting up timers
56
// - Initializing third-party libraries
57
58
timer = setInterval(() => {
59
console.log("Timer tick");
60
}, 1000);
61
});
62
63
onBeforeUnmount(() => {
64
console.log("Component is about to be unmounted");
65
// Clean up before unmount
66
if (timer) {
67
clearInterval(timer);
68
}
69
});
70
71
onUnmounted(() => {
72
console.log("Component has been unmounted");
73
// Final cleanup
74
data.value = null;
75
});
76
77
return { data };
78
}
79
});
80
```
81
82
### Update Hooks
83
84
Hooks for component update phases when reactive data changes.
85
86
```typescript { .api }
87
/**
88
* Registers a callback to be called before the component updates
89
* @param hook - Callback function to execute
90
*/
91
function onBeforeUpdate(hook: () => void): void;
92
93
/**
94
* Registers a callback to be called after the component updates
95
* @param hook - Callback function to execute
96
*/
97
function onUpdated(hook: () => void): void;
98
```
99
100
**Usage Examples:**
101
102
```typescript
103
import { defineComponent, ref, onBeforeUpdate, onUpdated } from "@vue/runtime-core";
104
105
const UpdateComponent = defineComponent({
106
setup() {
107
const count = ref(0);
108
const prevCount = ref(0);
109
110
onBeforeUpdate(() => {
111
console.log("Component is about to update");
112
// Capture current state before update
113
prevCount.value = count.value;
114
});
115
116
onUpdated(() => {
117
console.log(`Component updated: ${prevCount.value} -> ${count.value}`);
118
// DOM has been updated
119
// Good place to:
120
// - Access updated DOM elements
121
// - Perform side effects based on new data
122
});
123
124
const increment = () => {
125
count.value++;
126
};
127
128
return {
129
count,
130
increment
131
};
132
}
133
});
134
```
135
136
### KeepAlive Hooks
137
138
Special hooks for components wrapped in `<KeepAlive>`.
139
140
```typescript { .api }
141
/**
142
* Registers a callback to be called when a kept-alive component is activated
143
* @param hook - Callback function to execute
144
*/
145
function onActivated(hook: () => void): void;
146
147
/**
148
* Registers a callback to be called when a kept-alive component is deactivated
149
* @param hook - Callback function to execute
150
*/
151
function onDeactivated(hook: () => void): void;
152
```
153
154
**Usage Examples:**
155
156
```typescript
157
import { defineComponent, ref, onActivated, onDeactivated, onMounted, onUnmounted } from "@vue/runtime-core";
158
159
const KeepAliveComponent = defineComponent({
160
setup() {
161
const isActive = ref(false);
162
let timer: NodeJS.Timeout;
163
164
onMounted(() => {
165
console.log("Component mounted (first time only)");
166
});
167
168
onActivated(() => {
169
console.log("Component activated (every time it becomes visible)");
170
isActive.value = true;
171
172
// Resume operations when component becomes active
173
timer = setInterval(() => {
174
console.log("Active component timer");
175
}, 1000);
176
});
177
178
onDeactivated(() => {
179
console.log("Component deactivated (every time it becomes hidden)");
180
isActive.value = false;
181
182
// Pause operations when component becomes inactive
183
if (timer) {
184
clearInterval(timer);
185
}
186
});
187
188
onUnmounted(() => {
189
console.log("Component unmounted (only when KeepAlive is destroyed)");
190
});
191
192
return { isActive };
193
}
194
});
195
```
196
197
### Debug Hooks
198
199
Development-only hooks for debugging render performance.
200
201
```typescript { .api }
202
/**
203
* Registers a callback to be called when reactive dependencies are tracked during render
204
* @param hook - Debug callback with dependency information
205
*/
206
function onRenderTracked(hook: DebuggerHook): void;
207
208
/**
209
* Registers a callback to be called when reactive dependencies trigger a re-render
210
* @param hook - Debug callback with trigger information
211
*/
212
function onRenderTriggered(hook: DebuggerHook): void;
213
214
type DebuggerHook = (e: DebuggerEvent) => void;
215
216
interface DebuggerEvent {
217
effect: ReactiveEffect;
218
target: object;
219
type: TrackOpTypes | TriggerOpTypes;
220
key: any;
221
newValue?: any;
222
oldValue?: any;
223
}
224
```
225
226
**Usage Examples:**
227
228
```typescript
229
import { defineComponent, ref, onRenderTracked, onRenderTriggered } from "@vue/runtime-core";
230
231
const DebugComponent = defineComponent({
232
setup() {
233
const count = ref(0);
234
const name = ref("Vue");
235
236
onRenderTracked((e) => {
237
console.log("Dependency tracked during render:", {
238
target: e.target,
239
key: e.key,
240
type: e.type
241
});
242
});
243
244
onRenderTriggered((e) => {
245
console.log("Re-render triggered by:", {
246
target: e.target,
247
key: e.key,
248
type: e.type,
249
oldValue: e.oldValue,
250
newValue: e.newValue
251
});
252
});
253
254
return {
255
count,
256
name,
257
increment: () => count.value++,
258
updateName: (newName: string) => name.value = newName
259
};
260
}
261
});
262
```
263
264
### Error Handling Hook
265
266
Hook for catching errors in descendant components.
267
268
```typescript { .api }
269
/**
270
* Registers a callback to be called when an error is captured from a descendant component
271
* @param hook - Error handler callback
272
*/
273
function onErrorCaptured(hook: ErrorCapturedHook): void;
274
275
type ErrorCapturedHook = (
276
err: unknown,
277
instance: ComponentInternalInstance | null,
278
info: string
279
) => boolean | void;
280
```
281
282
**Usage Examples:**
283
284
```typescript
285
import { defineComponent, onErrorCaptured } from "@vue/runtime-core";
286
287
const ErrorBoundaryComponent = defineComponent({
288
setup() {
289
const errorMessages = ref<string[]>([]);
290
291
onErrorCaptured((error, instance, info) => {
292
console.error("Error captured:", error);
293
console.log("Error info:", info);
294
console.log("Component instance:", instance);
295
296
errorMessages.value.push(`${error}: ${info}`);
297
298
// Return false to prevent the error from propagating further
299
return false;
300
});
301
302
return {
303
errorMessages
304
};
305
}
306
});
307
```
308
309
### Server-Side Rendering Hook
310
311
Hook for server-side rendering data prefetching.
312
313
```typescript { .api }
314
/**
315
* Registers a callback to be called during server-side rendering for data prefetching
316
* @param hook - Async callback for data prefetching
317
*/
318
function onServerPrefetch(hook: () => Promise<any>): void;
319
```
320
321
**Usage Examples:**
322
323
```typescript
324
import { defineComponent, ref, onServerPrefetch, onMounted } from "@vue/runtime-core";
325
326
const SSRComponent = defineComponent({
327
setup() {
328
const data = ref(null);
329
const loading = ref(true);
330
331
const fetchData = async () => {
332
// Simulate API call
333
const response = await fetch('/api/data');
334
data.value = await response.json();
335
loading.value = false;
336
};
337
338
onServerPrefetch(async () => {
339
// This runs only on the server during SSR
340
await fetchData();
341
console.log("Data prefetched on server");
342
});
343
344
onMounted(() => {
345
// This runs only on the client
346
if (data.value === null) {
347
// Data wasn't prefetched (client-only rendering)
348
fetchData();
349
}
350
});
351
352
return {
353
data,
354
loading
355
};
356
}
357
});
358
```
359
360
## Lifecycle Execution Order
361
362
The lifecycle hooks execute in the following order:
363
364
### Component Creation & Mounting
365
1. `setup()` - Composition API setup
366
2. `onBeforeMount()` - Before DOM mounting
367
3. `onMounted()` - After DOM mounting
368
369
### Component Updates
370
1. `onBeforeUpdate()` - Before re-render
371
2. `onUpdated()` - After re-render and DOM update
372
373
### Component KeepAlive (if applicable)
374
1. `onActivated()` - When component becomes active
375
2. `onDeactivated()` - When component becomes inactive
376
377
### Component Unmounting
378
1. `onBeforeUnmount()` - Before unmounting
379
2. `onUnmounted()` - After unmounting
380
381
### Error Handling (when errors occur)
382
1. `onErrorCaptured()` - When descendant error is captured
383
384
### SSR (server-side only)
385
1. `onServerPrefetch()` - During server-side rendering
386
387
## Usage Notes
388
389
- All lifecycle hooks must be called synchronously during the component's setup phase
390
- Hooks can be called multiple times to register multiple callbacks
391
- Hooks are automatically bound to the current component instance
392
- In SSR, only `onServerPrefetch` runs on the server; others run on the client during hydration
393
- `onRenderTracked` and `onRenderTriggered` only work in development mode
394
- `onActivated` and `onDeactivated` only work for components wrapped in `<KeepAlive>`