📖 Scenario: You are building a Vue 3 app that needs to track the window width and update it reactively when the window is resized.
🎯 Goal: Create a composable function that uses Vue lifecycle hooks to track and update the window width reactively.
📋 What You'll Learn
Create a reactive variable to store the window width
Use the onMounted lifecycle hook to add a window resize event listener
Use the onUnmounted lifecycle hook to remove the event listener
Return the reactive window width variable from the composable
💡 Why This Matters
🌍 Real World
Tracking window size is common in responsive design to adapt UI elements dynamically.
💼 Career
Understanding composables and lifecycle hooks is essential for building maintainable Vue 3 applications.
Progress0 / 4 steps
1
Create a reactive variable for window width
Create a composable function called useWindowWidth that defines a reactive variable width initialized to window.innerWidth using Vue's ref.
Vue
Hint
Use ref from Vue to create a reactive variable.
2
Add onMounted lifecycle hook to listen for resize
Inside the useWindowWidth function, import and use Vue's onMounted hook to add a resize event listener on window. The listener should update width.value to window.innerWidth.
Vue
Hint
Use onMounted to add the event listener only after the component is mounted.
3
Add onUnmounted lifecycle hook to remove listener
Import Vue's onUnmounted hook and use it inside useWindowWidth to remove the resize event listener from window when the component unmounts. Store the listener function in a variable called updateWidth.
Vue
Hint
Define the listener function separately so you can remove it later.
4
Return the reactive width variable
At the end of the useWindowWidth function, return an object with the width reactive variable so components can use it.
Vue
Hint
Return the reactive variable inside an object for easy destructuring.
Practice
(1/5)
1. What is the main purpose of using lifecycle hooks inside a Vue composable?
easy
A. To run code automatically when a component starts or stops
B. To define the component's template structure
C. To style the component with CSS
D. To create new Vue components
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 A
Quick Check:
Lifecycle hooks run code at component start/stop = A [OK]
Hint: Lifecycle hooks run code on component start or cleanup [OK]
Common Mistakes:
Thinking lifecycle hooks define templates
Confusing styling with lifecycle hooks
Believing composables create components
2. Which of the following is the correct way to import and use the onMounted lifecycle hook inside a Vue 3 composable?
easy
A. import { onMounted } from 'vue'; onMounted = () => { /* code */ };
B. import onMounted from 'vue'; onMounted(() => { /* code */ });
C. import { onMounted } from 'vue'; onMounted(() => { /* code */ });
D. import { onMounted } from 'vue'; onMounted.function(() => { /* code */ });
Solution
Step 1: Check import syntax
Vue lifecycle hooks like onMounted are named exports, so use curly braces in import.
Step 2: Check usage syntax
onMounted is a function that takes a callback, so call it with a function argument.
Final Answer:
import { onMounted } from 'vue'; onMounted(() => { /* code */ }); -> Option C
Quick Check:
Correct import and call syntax = A [OK]
Hint: Use curly braces to import lifecycle hooks from 'vue' [OK]
Common Mistakes:
Importing without curly braces
Assigning onMounted to a function instead of calling it
Using incorrect method like onMounted.function
3. Given this composable code, what will be logged when a component using it is mounted?
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.