Discover how to write setup code once and reuse it everywhere without headaches!
Why Composable with lifecycle hooks in Vue? - Purpose & Use Cases
Imagine you have multiple Vue components that need to run similar setup code when they start, like fetching data or setting timers. You copy and paste this code into each component's lifecycle hooks.
Copying code everywhere makes your app hard to maintain. If you want to change the logic, you must update every component. It's easy to forget one, causing bugs. Also, mixing setup code inside components clutters them and hides the real purpose.
Composable functions with lifecycle hooks let you write reusable setup logic once. You call these composables inside components, and they automatically connect to the component's lifecycle. This keeps your code clean, DRY, and easy to update.
export default { mounted() { this.startTimer() }, methods: { startTimer() { /* timer logic */ } } }import { onMounted } from 'vue'; function useTimer() { onMounted(() => { /* timer logic */ }) } export default { setup() { useTimer() } }
You can share complex setup logic across components effortlessly, making your app easier to build and maintain.
Imagine a chat app where many components need to connect to a WebSocket when they mount. Using a composable with lifecycle hooks, you write the connection logic once and reuse it everywhere.
Manual lifecycle code copying leads to bugs and clutter.
Composables with lifecycle hooks let you reuse setup logic cleanly.
This approach improves maintainability and clarity in Vue apps.
Practice
Solution
Step 1: Understand lifecycle hooks role
Lifecycle hooks let you run code at specific times in a component's life, like when it starts or stops.Step 2: Connect lifecycle hooks with composables
Using lifecycle hooks inside composables allows shared logic to run automatically when components use the composable.Final Answer:
To run code automatically when a component starts or stops -> Option AQuick Check:
Lifecycle hooks run code at component start/stop = A [OK]
- Thinking lifecycle hooks define templates
- Confusing styling with lifecycle hooks
- Believing composables create components
onMounted lifecycle hook inside a Vue 3 composable?Solution
Step 1: Check import syntax
Vue lifecycle hooks likeonMountedare named exports, so use curly braces in import.Step 2: Check usage syntax
onMountedis a function that takes a callback, so call it with a function argument.Final Answer:
import { onMounted } from 'vue'; onMounted(() => { /* code */ }); -> Option CQuick Check:
Correct import and call syntax = A [OK]
- Importing without curly braces
- Assigning onMounted to a function instead of calling it
- Using incorrect method like onMounted.function
import { ref, onMounted } from 'vue';
export function useLogger() {
const message = ref('Hello');
onMounted(() => {
console.log(message.value);
});
return { message };
}Solution
Step 1: Understand ref initialization
Themessageref is initialized with the string 'Hello'.Step 2: Check onMounted callback
When the component mounts, the callback logsmessage.value, which is 'Hello'.Final Answer:
Hello -> Option AQuick Check:
Ref value logged on mount = B [OK]
- Logging ref without .value
- Expecting undefined before mount
- Thinking onMounted runs before ref initialization
import { onMounted, onUnmounted } from 'vue';
export function useTimer() {
let timer = null;
onMounted(() => {
timer = setInterval(() => console.log('tick'), 1000);
});
onUnmounted(() => {
clearInterval(timer);
});
return {};
}Solution
Step 1: Check variable scope and usage
Variabletimeris declared in composable scope and updated inonMounted, accessible inonUnmounted.Step 2: Verify lifecycle hooks usage
onMountedsets interval,onUnmountedclears it correctly to avoid memory leaks.Final Answer:
No error, code works correctly -> Option DQuick Check:
Proper timer setup and cleanup = D [OK]
- Thinking timer must be a ref
- Confusing onUnmounted with onBeforeUnmount
- Misunderstanding setInterval callback syntax
Solution
Step 1: Determine when to start fetch
Fetching data should start when the component is fully mounted, so useonMounted.Step 2: Handle cleanup on unmount
To cancel fetch if component unmounts early, useonUnmountedto abort the fetch using an AbortController.Final Answer:
UseonMountedto start fetch andonUnmountedto abort fetch with an AbortController -> Option BQuick Check:
Fetch start on mount, abort on unmount = C [OK]
- Starting fetch too early or too late
- Not aborting fetch on unmount causing leaks
- Using wrong lifecycle hooks for cleanup
Ready to prove it?
Pass the test and this pattern moves unknown
