0
0
VueConceptBeginner · 4 min read

Vue Lifecycle Hooks: What They Are and How They Work

In Vue, lifecycle hooks are special functions that run at specific stages of a component's life, like creation, update, or destruction. They let you add code to react to these stages, such as fetching data when a component appears or cleaning up before it disappears.
⚙️

How It Works

Think of a Vue component like a living creature that goes through different stages: it is born, grows, changes, and eventually disappears. Lifecycle hooks are like checkpoints during these stages where you can run your own code to do something important.

For example, when a component is created but not yet shown on the screen, you might want to prepare some data. When it appears on the screen, you might start animations or fetch information from the internet. When it is about to be removed, you might stop timers or save data. Vue provides these hooks so you can easily plug in your code at the right moments.

💻

Example

This example shows a Vue component using two lifecycle hooks: mounted and beforeUnmount. It logs messages when the component appears and just before it disappears.

javascript
import { defineComponent, onMounted, onBeforeUnmount } from 'vue';

export default defineComponent({
  name: 'LifecycleDemo',
  setup() {
    onMounted(() => {
      console.log('Component is now mounted (shown on screen)');
    });

    onBeforeUnmount(() => {
      console.log('Component is about to be removed');
    });

    return {};
  }
});
Output
Component is now mounted (shown on screen) Component is about to be removed
🎯

When to Use

Use lifecycle hooks whenever you need to run code tied to a component's life. Common uses include:

  • Fetching data when the component appears (mounted).
  • Setting up event listeners or timers when the component starts.
  • Cleaning up resources like timers or subscriptions before the component is removed (beforeUnmount).
  • Reacting to changes in the component's data or props.

For example, if you build a chat app, you might open a WebSocket connection when the chat window shows and close it when the user leaves.

Key Points

  • Lifecycle hooks run automatically at specific component stages.
  • They help manage side effects like data fetching and cleanup.
  • Vue 3 uses the setup() function with hooks like onMounted and onBeforeUnmount.
  • Hooks improve code organization and component control.

Key Takeaways

Lifecycle hooks let you run code at key moments in a Vue component's life.
Use hooks to fetch data, set up, or clean up resources tied to the component.
Vue 3 uses functions like onMounted and onBeforeUnmount inside setup().
Hooks help keep your component code organized and predictable.