What are Lifecycle Hooks?
Lifecycle hooks are special methods in Vue that allow you to run code at specific stages of a component's life.
Lifecycle Phases
| Phase | Hooks |
|---|---|
| Creation | created |
| Mounting | beforeMount, mounted |
| Updating | beforeUpdate, updated |
| Unmounting | beforeUnmount, unmounted |
created Hook
Called when the component is created but not yet mounted to the DOM.
JavaScriptRead-only
1
mounted Hook
Called after the component is mounted to the DOM.
JavaScriptRead-only
1
updated Hook
Called when reactive data changes and the DOM updates.
JavaScriptRead-only
1
unmounted Hook
Called when the component is removed from the DOM.
JavaScriptRead-only
1
Use Cases
- Fetch data in mounted()
- Initialize variables in created()
- Watch DOM updates in updated()
- Cleanup resources in unmounted()
Best Practices
- Use mounted for DOM-related logic
- Avoid heavy logic in updated
- Clean up timers and listeners in unmounted
- Use created for initial setup
Common Mistakes
- Using DOM before mounted
- Heavy operations in updated hook
- Not cleaning resources in unmounted
- Confusing created and mounted hooks
Conclusion
Lifecycle hooks are essential for controlling component behavior at different stages, enabling efficient and organized Vue applications.