0
0
Vueframework~15 mins

Lifecycle hooks in Composition API in Vue - Deep Dive

Choose your learning style9 modes available
Overview - Lifecycle hooks in Composition API
What is it?
Lifecycle hooks in the Composition API are special functions that let you run code at specific times during a Vue component's life. These times include when the component is created, updated, or destroyed. They help you organize side effects like fetching data or cleaning up resources. Using these hooks, you control what happens behind the scenes as your component appears and disappears.
Why it matters
Without lifecycle hooks, you would have no way to react to important moments in a component's life, like when it first shows up or when it goes away. This would make managing things like data loading, timers, or event listeners very messy and error-prone. Lifecycle hooks keep your code organized and efficient, making your app more reliable and easier to maintain.
Where it fits
Before learning lifecycle hooks, you should understand the basics of Vue components and the Composition API's reactive system. After mastering lifecycle hooks, you can explore advanced topics like custom composables, state management, and performance optimization in Vue apps.
Mental Model
Core Idea
Lifecycle hooks are like checkpoints in a component’s life where you can run code to prepare, update, or clean up resources.
Think of it like...
Imagine a theater play: lifecycle hooks are the moments when actors enter the stage, perform, take breaks, or leave. You prepare before the scene, act during it, and tidy up after.
┌───────────────┐
│ Component     │
│ Lifecycle     │
│ Timeline      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ onBeforeMount │  ← Just before component appears
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ onMounted     │  ← Component is now visible
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ onUpdated     │  ← After reactive data changes
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ onBeforeUnmount│ ← Just before component is removed
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ onUnmounted   │  ← Component is removed, cleanup
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Vue Component Lifecycle
🤔
Concept: Learn what a component lifecycle means and why it matters in Vue.
A Vue component goes through stages: creation, rendering, updating, and destruction. Each stage is a chance to run code to prepare or clean up. This lifecycle is automatic and helps Vue manage your app efficiently.
Result
You know the basic stages a component passes through and why timing matters.
Understanding the lifecycle stages helps you know when to run your code for best effect.
2
FoundationIntroduction to Composition API Setup
🤔
Concept: Learn how the Composition API organizes component logic inside a setup() function.
In Vue's Composition API, all reactive data and logic live inside the setup() function. This is where you declare state, functions, and lifecycle hooks. It replaces the older Options API's separate sections.
Result
You can create a basic component using setup() and understand where lifecycle hooks fit.
Knowing setup() is key because lifecycle hooks are called inside it, making your code more organized.
3
IntermediateUsing Basic Lifecycle Hooks in Composition API
🤔Before reading on: Do you think lifecycle hooks run automatically or need manual calls? Commit to your answer.
Concept: Learn how to use onMounted and onUnmounted hooks to run code when a component appears or disappears.
Vue provides functions like onMounted() and onUnmounted() that you call inside setup(). For example, onMounted(() => { /* code */ }) runs after the component is shown. onUnmounted(() => { /* cleanup */ }) runs before the component is removed.
Result
You can run code to fetch data when the component appears and clean up timers when it disappears.
Knowing these hooks run automatically at the right time helps you manage side effects cleanly.
4
IntermediateExploring Additional Lifecycle Hooks
🤔Before reading on: Which do you think runs first: onBeforeMount or onMounted? Commit to your answer.
Concept: Discover other hooks like onBeforeMount, onUpdated, and onBeforeUnmount for finer control.
onBeforeMount runs just before the component renders. onUpdated runs after reactive data changes cause a re-render. onBeforeUnmount runs just before the component is removed. Using these lets you react precisely at different lifecycle moments.
Result
You can prepare data before showing, respond to updates, and clean up before removal.
Understanding the order and purpose of these hooks lets you write more predictable and bug-free code.
5
IntermediateCleaning Up with onUnmounted Hook
🤔
Concept: Learn why cleaning up resources like timers or event listeners is crucial using onUnmounted.
If you start timers or add event listeners in your component, you must remove them when the component is gone. Otherwise, they keep running and cause bugs or memory leaks. Use onUnmounted(() => { /* cleanup code */ }) to do this safely.
Result
Your app stays fast and bug-free by avoiding leftover processes.
Knowing to clean up prevents common performance and bug issues in real apps.
6
AdvancedCombining Multiple Lifecycle Hooks in One Component
🤔Before reading on: Can you use multiple lifecycle hooks together in one setup()? Commit to yes or no.
Concept: Learn how to use several lifecycle hooks together to handle complex component behavior.
Inside setup(), you can call multiple hooks like onBeforeMount, onMounted, onUpdated, and onUnmounted. This lets you manage initialization, updates, and cleanup in one place. For example, fetch data on mount, watch changes on update, and clear timers on unmount.
Result
You can build components that react properly at every lifecycle stage.
Understanding how hooks combine lets you build robust, maintainable components.
7
ExpertLifecycle Hooks and Async Setup Interaction
🤔Before reading on: Does async setup() delay lifecycle hooks like onMounted? Commit to your answer.
Concept: Explore how lifecycle hooks behave when setup() is async and how to handle async side effects.
If setup() returns a Promise (async), Vue waits for it before mounting. However, lifecycle hooks like onMounted still run after mounting. You can use async functions inside hooks for side effects. Be careful to handle errors and cleanup properly to avoid subtle bugs.
Result
You can safely use async code with lifecycle hooks without breaking component flow.
Knowing the timing and async behavior prevents bugs in complex data fetching or initialization.
Under the Hood
Vue tracks component instances and their reactive dependencies. When a component is created, Vue sets up reactive tracking and calls lifecycle hooks at defined points. Hooks are stored as callbacks linked to the component instance. When the component updates or unmounts, Vue triggers these callbacks in order. This system ensures side effects run exactly when needed without manual intervention.
Why designed this way?
Vue's lifecycle hooks were designed to separate concerns: setup, rendering, updating, and cleanup. This clear separation helps developers write predictable code and Vue to optimize rendering. The Composition API hooks unify lifecycle management inside setup(), improving code organization and reusability compared to the older Options API.
┌───────────────┐
│ Component     │
│ Instance      │
├───────────────┤
│ Reactive Data │
│ Tracking      │
├───────────────┤
│ Lifecycle     │
│ Hook Callbacks│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Vue Runtime   │
│ Scheduler    │
│ Calls Hooks  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think onMounted runs before or after the component appears? Commit to your answer.
Common Belief:onMounted runs before the component is visible on screen.
Tap to reveal reality
Reality:onMounted runs after the component has been mounted and is visible in the DOM.
Why it matters:Running code too early can cause errors if the DOM elements are not ready, leading to bugs or failed operations.
Quick: Can you call lifecycle hooks outside setup()? Commit to yes or no.
Common Belief:Lifecycle hooks can be called anywhere in the component code.
Tap to reveal reality
Reality:Lifecycle hooks must be called inside the setup() function to work correctly.
Why it matters:Calling hooks outside setup() means Vue won't register them, so your code won't run at the right time.
Quick: Does onUnmounted run immediately when a component is hidden? Commit to your answer.
Common Belief:onUnmounted runs whenever the component is hidden or not visible.
Tap to reveal reality
Reality:onUnmounted runs only when the component is removed from the DOM, not just hidden.
Why it matters:Misunderstanding this can cause premature cleanup, breaking functionality when components are toggled.
Quick: Do you think async setup delays onMounted? Commit to yes or no.
Common Belief:If setup() is async, onMounted waits until setup finishes.
Tap to reveal reality
Reality:Vue waits for async setup() before mounting, so onMounted runs after setup resolves, but async code inside onMounted still runs after mount.
Why it matters:Knowing this prevents timing bugs in data fetching and UI updates.
Expert Zone
1
Lifecycle hooks in Composition API are tied to the component instance context, so using them outside setup or composables linked to the instance breaks reactivity.
2
Using onUpdated too often can cause performance issues; it's best to watch specific reactive sources instead for fine-grained updates.
3
Cleanup in onUnmounted must handle all side effects started in setup, including those from nested composables, to avoid memory leaks.
When NOT to use
Avoid using lifecycle hooks for simple reactive data changes; instead, use watchers or computed properties. For global app-level side effects, use plugins or provide/inject patterns rather than component lifecycle hooks.
Production Patterns
In real apps, lifecycle hooks are used to fetch data on mount, subscribe to events, start animations, and clean up timers or listeners on unmount. Developers often combine hooks with composables to share lifecycle-aware logic across components.
Connections
Reactive Programming
Lifecycle hooks work closely with reactive data changes to trigger updates and side effects.
Understanding reactive programming helps grasp why lifecycle hooks run at certain times and how to optimize component updates.
Event-driven Systems
Lifecycle hooks act like event listeners for component state changes.
Knowing event-driven design clarifies how hooks respond to lifecycle events, improving your ability to manage side effects.
Theater Production
Both involve managing stages and timing for actors/components to appear, perform, and exit.
Recognizing lifecycle hooks as stage cues helps you plan component behavior smoothly and predictably.
Common Pitfalls
#1Starting a timer in setup() but forgetting to clear it on unmount.
Wrong approach:setup() { setInterval(() => console.log('tick'), 1000); }
Correct approach:setup() { const timer = setInterval(() => console.log('tick'), 1000); onUnmounted(() => clearInterval(timer)); }
Root cause:Not understanding that side effects must be cleaned up to avoid memory leaks.
#2Calling lifecycle hooks outside setup(), expecting them to run.
Wrong approach:onMounted(() => { console.log('Hello'); }); export default { /* component */ }
Correct approach:export default { setup() { onMounted(() => { console.log('Hello'); }); } }
Root cause:Misunderstanding that hooks must be registered inside setup() to link to the component instance.
#3Using onUpdated to watch all changes instead of specific reactive data.
Wrong approach:setup() { onUpdated(() => { console.log('Component updated'); }); }
Correct approach:setup() { const count = ref(0); watch(count, () => { console.log('Count changed'); }); }
Root cause:Not realizing onUpdated runs on every update, causing unnecessary work and performance issues.
Key Takeaways
Lifecycle hooks in the Composition API let you run code at key moments in a component's life, like mounting and unmounting.
They must be called inside the setup() function to work properly and keep your code organized.
Using hooks like onMounted and onUnmounted helps manage side effects such as data fetching and cleanup safely.
Understanding the order and timing of hooks prevents bugs and improves app performance.
Advanced use includes combining multiple hooks and handling async setup to build robust Vue components.