Lifecycle hooks let you run code at specific moments in a component’s life. In Composition API, import hooks from Vue and call them inside setup().
Common hooks
onBeforeMount/onMounted— before/after DOM is createdonBeforeUpdate/onUpdated— around re-rendersonBeforeUnmount/onUnmounted— teardown (timers, subscriptions)
Typical onMounted uses
- Fetch data when the component appears
- Initialize third-party libraries that need DOM nodes
- Focus an input or measure layout
Cleanup
Pair side effects with onUnmounted—clear intervals, abort fetches, remove listeners. Same discipline as React useEffect cleanup.
Self-check
- When does
onMountedrun relative to the first paint? - Where should you clear a
setInterval?
Challenge
Document title
- Type in the input and watch
document.titleupdate (check the browser tab in the iframe). - Confirm
onUnmountedresets the title when you re-run with different code.
Done when: document.title matches the input while the component is mounted.