Composable functions help you reuse code in Vue components. Lifecycle hooks inside composables let you run code at key moments like when a component starts or stops.
You want to share logic like fetching data or timers between components.
You need to run setup or cleanup code when a component mounts or unmounts.
You want to keep your component code clean by moving side effects to composables.
You want to react to component lifecycle events inside reusable functions.
Syntax
Vue
import { onMounted, onUnmounted } from'vue';
exportfunction useExample() {
onMounted(() => {
// code to run when component mounts
});
onUnmounted(() => {
// code to run when component unmounts
});
return {
// reactive data or methods
};
}
Use onMounted to run code after the component appears on screen.
Use onUnmounted to clean up when the component is removed.
Examples
This composable logs a message when the component mounts.
This Vue component uses a composable useTimer that starts counting seconds when the component mounts and stops when it unmounts. The seconds count updates every second and shows on screen.
Variable timer is declared in composable scope and updated in onMounted, accessible in onUnmounted.
Step 2: Verify lifecycle hooks usage
onMounted sets interval, onUnmounted clears it correctly to avoid memory leaks.
Final Answer:
No error, code works correctly -> Option D
Quick Check:
Proper timer setup and cleanup = D [OK]
Hint: Variables in composable scope persist across lifecycle hooks [OK]
Common Mistakes:
Thinking timer must be a ref
Confusing onUnmounted with onBeforeUnmount
Misunderstanding setInterval callback syntax
5. You want to create a composable that fetches data when a component mounts and cancels the fetch if the component unmounts before completion. Which lifecycle hooks and pattern should you use inside the composable?
hard
A. Use onUnmounted to start fetch and onMounted to abort fetch
B. Use onMounted to start fetch and onUnmounted to abort fetch with an AbortController
C. Use onBeforeMount to start fetch and onMounted to abort fetch
D. Use onMounted to start fetch and no cleanup is needed
Solution
Step 1: Determine when to start fetch
Fetching data should start when the component is fully mounted, so use onMounted.
Step 2: Handle cleanup on unmount
To cancel fetch if component unmounts early, use onUnmounted to abort the fetch using an AbortController.
Final Answer:
Use onMounted to start fetch and onUnmounted to abort fetch with an AbortController -> Option B
Quick Check:
Fetch start on mount, abort on unmount = C [OK]
Hint: Start fetch on mount, abort on unmount with AbortController [OK]
Common Mistakes:
Starting fetch too early or too late
Not aborting fetch on unmount causing leaks
Using wrong lifecycle hooks for cleanup
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.