0
0
Vueframework~5 mins

Composable with lifecycle hooks in Vue - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a composable in Vue 3?
A composable is a reusable function that uses Vue's Composition API to encapsulate and share reactive state and logic across components.
Click to reveal answer
beginner
Which Vue lifecycle hook is used to run code when a component is mounted?
The onMounted lifecycle hook runs code after the component is inserted into the DOM.
Click to reveal answer
intermediate
How do you use lifecycle hooks inside a composable?
You import the lifecycle hook functions like <code>onMounted</code> from Vue and call them inside the composable function to run code at specific component lifecycle stages.
Click to reveal answer
intermediate
Why use lifecycle hooks inside composables?
Using lifecycle hooks inside composables lets you keep related logic and side effects together, making your code cleaner and easier to reuse across components.
Click to reveal answer
intermediate
Example: What does this composable do?
<pre>import { ref, onMounted } from 'vue';
export function useTimer() {
  const time = ref(0);
  onMounted(() => {
    setInterval(() => {
      time.value++;
    }, 1000);
  });
  return { time };
}</pre>
This composable useTimer creates a reactive time value that increases by 1 every second after the component using it is mounted.
Click to reveal answer
What is the purpose of the onUnmounted lifecycle hook in a composable?
ATo update the template
BTo run code before the component is mounted
CTo initialize reactive state
DTo run code when the component is removed from the DOM
Where do you import lifecycle hooks like onMounted when creating a composable?
AFrom 'axios'
BFrom 'vue-router'
CFrom 'vue' package
DFrom 'vuex'
What happens if you call onMounted outside a composable or component setup function?
AIt will cause an error or not work properly
BIt will run immediately
CIt will delay the component mounting
DIt will update the DOM
Which of these is a benefit of using composables with lifecycle hooks?
ABetter code reuse and organization
BSlower app performance
CMore complex templates
DLess reactive state
In the example composable useTimer, when does the timer start counting?
AImmediately when the composable is imported
BAfter the component is mounted
CBefore the component is created
DWhen the component is unmounted
Explain how to create a composable in Vue that uses lifecycle hooks to start and stop a timer.
Think about how to manage side effects with lifecycle hooks inside a reusable function.
You got /4 concepts.
    Describe why lifecycle hooks are important when writing composables in Vue.
    Consider what happens when components mount and unmount.
    You got /4 concepts.