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?✗ Incorrect
onUnmounted runs cleanup code when the component is removed from the DOM, such as clearing timers or event listeners.
Where do you import lifecycle hooks like
onMounted when creating a composable?✗ Incorrect
Lifecycle hooks are imported directly from the core vue package.
What happens if you call
onMounted outside a composable or component setup function?✗ Incorrect
Lifecycle hooks must be called inside setup functions or composables used in setup; otherwise, Vue cannot link them to the component lifecycle.
Which of these is a benefit of using composables with lifecycle hooks?
✗ Incorrect
Composables with lifecycle hooks help organize logic and reuse it easily across components.
In the example composable
useTimer, when does the timer start counting?✗ Incorrect
The timer starts inside the onMounted hook, so it begins after the component is mounted.
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.