Vue activated Lifecycle Hook

Welcome to The Coding College! In this guide, we’ll explore the activated lifecycle hook in Vue.js, a useful feature for managing reusable dynamic components, especially when working with <KeepAlive>.

What is the activated Lifecycle Hook?

The activated hook in Vue 3 (and Vue 2) is a special lifecycle hook that triggers when a cached component inside a <KeepAlive> wrapper becomes active again. This hook allows you to manage state and behavior specifically for components that are reused through caching.

When Does activated Trigger?

The activated hook is called whenever:

  1. A cached component inside a <KeepAlive> is rendered again (becomes active).

It pairs with the deactivated hook, which triggers when the same cached component is hidden (inactive).

Syntax

Using the Options API

<script>
export default {
  activated() {
    console.log('Component activated');
  },
  deactivated() {
    console.log('Component deactivated');
  }
};
</script>

Using the Composition API

import { onActivated, onDeactivated } from 'vue';

export default {
  setup() {
    onActivated(() => {
      console.log('Component activated');
    });

    onDeactivated(() => {
      console.log('Component deactivated');
    });
  }
};

Example: Managing Cached Components

Here’s a common example where <KeepAlive> is used to cache components, and the activated hook is used to refresh or manage data when the component becomes active again.

Example Code

<template>
  <div>
    <button @click="currentView = 'ComponentA'">Show Component A</button>
    <button @click="currentView = 'ComponentB'">Show Component B</button>
    <KeepAlive>
      <component :is="currentView" />
    </KeepAlive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentView: 'ComponentA'
    };
  },
  components: {
    ComponentA: {
      template: `<p>Component A</p>`,
      activated() {
        console.log('Component A activated');
      },
      deactivated() {
        console.log('Component A deactivated');
      }
    },
    ComponentB: {
      template: `<p>Component B</p>`,
      activated() {
        console.log('Component B activated');
      },
      deactivated() {
        console.log('Component B deactivated');
      }
    }
  }
};
</script>

Example Output

When you switch between components, the console logs:

Component A deactivated
Component B activated

Use Cases for activated

1. Refreshing Data When a Component Becomes Active

You can use activated to refresh or re-fetch data when a cached component is displayed again.

activated() {
  console.log('Fetching data...');
  this.fetchData();
}

2. Resuming State or Animations

Pause and resume animations or timers when components toggle between active and inactive states.

activated() {
  this.startAnimation();
},
deactivated() {
  this.pauseAnimation();
}

3. Performance Optimization

Avoid fetching data or resetting state unnecessarily for cached components by relying on activated to handle updates only when required.

Advanced Example

Cache with Data Refresh

<template>
  <div>
    <KeepAlive>
      <MyComponent />
    </KeepAlive>
  </div>
</template>

<script>
export default {
  components: {
    MyComponent: {
      data() {
        return { message: 'Hello' };
      },
      template: `<p>{{ message }}</p>`,
      methods: {
        fetchData() {
          this.message = 'Data refreshed!';
          console.log('Data fetched.');
        }
      },
      activated() {
        this.fetchData();
      },
      deactivated() {
        console.log('Component deactivated.');
      }
    }
  }
};
</script>

Output

When the component becomes active again, it fetches new data:

Data fetched.
Component deactivated.
Data fetched.

Tips for Using activated

  1. Use with <KeepAlive> Only
    The activated hook only works for components wrapped in <KeepAlive>.
  2. Pair with deactivated
    Combine activated and deactivated for comprehensive control over reusable components.
  3. Optimize Data Fetching
    Only fetch or refresh data in activated when absolutely necessary to avoid redundant calls.

Limitations

  • Works Only with <KeepAlive>: The activated hook has no effect on non-cached components.
  • Requires Proper Cache Management: Overusing <KeepAlive> can increase memory usage and reduce performance if too many components are cached simultaneously.

Conclusion

The activated lifecycle hook is a powerful tool for managing cached components in Vue.js. By using it in combination with <KeepAlive>, you can enhance user experience, optimize performance, and maintain component state efficiently.

Key Takeaways:

  • Use activated to refresh or manage state when a cached component is reused.
  • Pair it with deactivated for comprehensive lifecycle management.
  • Ideal for components that benefit from caching, such as tab views or paginated lists.

Explore more advanced Vue concepts and tutorials at The Coding College!

Leave a Comment