Bird
Raised Fist0
Vueframework~20 mins

onMounted and onUnmounted in Vue - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Vue Lifecycle Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a Vue component using onMounted runs?

Consider a Vue 3 component that uses onMounted to log a message. What will you see in the browser console when the component first appears?

Vue
import { onMounted } from 'vue';

export default {
  setup() {
    onMounted(() => {
      console.log('Component is now mounted');
    });
  }
}
AThe message 'Component is now mounted' appears once in the console when the component is added to the page.
BThe message appears repeatedly every second after the component mounts.
CThe message appears before the component is rendered on the page.
DNo message appears because onMounted only works with class components.
Attempts:
2 left
💡 Hint

Think about when onMounted runs in the component lifecycle.

❓ component_behavior
intermediate
2:00remaining
What is the effect of onUnmounted in a Vue component?

In a Vue 3 component, onUnmounted is used to clean up resources. What happens when the component is removed from the page?

Vue
import { onUnmounted } from 'vue';

export default {
  setup() {
    onUnmounted(() => {
      console.log('Component is now unmounted');
    });
  }
}
AThe message appears when the component is first created.
BThe message appears every time the component updates.
CThe message 'Component is now unmounted' appears once in the console when the component is removed from the page.
DNo message appears because onUnmounted only works with class components.
Attempts:
2 left
💡 Hint

Remember when onUnmounted runs in the component lifecycle.

❓ state_output
advanced
2:00remaining
What is the console output when using both onMounted and onUnmounted in a Vue component?

Given this Vue 3 component, what will the console show when the component is mounted and then unmounted?

Vue
import { ref, onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    const count = ref(0);

    onMounted(() => {
      console.log('Mounted with count:', count.value);
    });

    onUnmounted(() => {
      console.log('Unmounted with count:', count.value);
    });

    return { count };
  }
}
AConsole logs 'Mounted with count: 0' when mounted and 'Unmounted with count: 0' when unmounted.
BConsole logs 'Mounted with count: 0' twice and no unmounted message.
CConsole logs only 'Unmounted with count: 0' when unmounted.
DNo console output because count is not updated.
Attempts:
2 left
💡 Hint

Think about when each lifecycle hook runs and the initial value of count.

🔧 Debug
advanced
2:00remaining
Why does this Vue component's onUnmounted callback never run?

Look at this Vue 3 component. Why does the message inside onUnmounted never appear in the console?

Vue
import { onUnmounted } from 'vue';

export default {
  setup() {
    onUnmounted(() => {
      console.log('Component unmounted');
    });
  },
  template: '<div>Test</div>'
};
AThe component is missing a <code>name</code> property, so hooks don't run.
B<code>onUnmounted</code> must be used inside <code>mounted()</code> hook to work.
CThe console.log is inside the wrong lifecycle hook; it should be <code>onBeforeUnmount</code>.
DThe component is never removed from the DOM, so <code>onUnmounted</code> never runs.
Attempts:
2 left
💡 Hint

Think about when onUnmounted runs and what triggers it.

🧠 Conceptual
expert
3:00remaining
How do onMounted and onUnmounted help manage side effects in Vue 3?

Which statement best explains the role of onMounted and onUnmounted in managing side effects like timers or event listeners?

A<code>onMounted</code> and <code>onUnmounted</code> only run once when the app starts and stops, not per component.
B<code>onMounted</code> sets up side effects after the component appears, and <code>onUnmounted</code> cleans them up when it disappears, preventing memory leaks.
C<code>onMounted</code> and <code>onUnmounted</code> are used only for updating the component's template, not for side effects.
D<code>onMounted</code> cleans up side effects before the component appears, and <code>onUnmounted</code> sets them up after it disappears.
Attempts:
2 left
💡 Hint

Think about how to avoid leftover timers or listeners after a component is gone.

Practice

(1/5)
1. What is the main purpose of the onMounted lifecycle hook in Vue?
easy
A. To run code when the component is destroyed
B. To run code before the component is created
C. To update the component's data reactively
D. To run code right after the component appears on the screen

Solution

  1. Step 1: Understand the lifecycle timing of onMounted

    The onMounted hook runs after the component is inserted into the DOM and visible to the user.
  2. Step 2: Compare with other lifecycle hooks

    onUnmounted runs before removal, and creation hooks run earlier. Updating data is reactive and not tied to onMounted.
  3. Final Answer:

    To run code right after the component appears on the screen -> Option D
  4. Quick Check:

    onMounted = runs after component appears [OK]
Hint: onMounted runs code after component shows up [OK]
Common Mistakes:
  • Confusing onMounted with onUnmounted
  • Thinking onMounted runs before creation
  • Assuming onMounted updates data reactively
2. Which of the following is the correct syntax to use onUnmounted in a Vue 3 component with Composition API?
easy
A. onUnmounted(() => { console.log('Component removed') })
B. onUnmounted = () => { console.log('Component removed') }
C. onUnmounted { console.log('Component removed') }
D. onUnmounted(function) { console.log('Component removed') }

Solution

  1. Step 1: Recall the correct function call syntax

    onUnmounted is a function that takes a callback function as an argument, so it must be called with parentheses and a function inside.
  2. Step 2: Check each option's syntax

    onUnmounted(() => { console.log('Component removed') }) correctly calls onUnmounted with an arrow function. Options B, C, and D have invalid syntax or missing parentheses.
  3. Final Answer:

    onUnmounted(() => { console.log('Component removed') }) -> Option A
  4. Quick Check:

    onUnmounted(callback) syntax correct [OK]
Hint: Use onUnmounted as a function with a callback [OK]
Common Mistakes:
  • Missing parentheses when calling onUnmounted
  • Assigning onUnmounted instead of calling it
  • Using incorrect braces or keywords
3. Consider this Vue 3 component code snippet:
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    let timer

    onMounted(() => {
      timer = setInterval(() => {
        count.value++
      }, 1000)
    })

    onUnmounted(() => {
      clearInterval(timer)
    })

    return { count }
  }
}

What will happen to count when the component is removed from the page?
medium
A. count will keep increasing even after component removal
B. count will stop increasing because the timer is cleared on unmount
C. count will reset to zero automatically
D. An error will occur because timer is undefined

Solution

  1. Step 1: Understand the timer setup in onMounted

    The code starts a timer that increments count every second when the component mounts.
  2. Step 2: Understand the cleanup in onUnmounted

    The timer is cleared with clearInterval(timer) when the component unmounts, stopping the increments.
  3. Final Answer:

    count will stop increasing because the timer is cleared on unmount -> Option B
  4. Quick Check:

    onUnmounted clears timer stopping count increment [OK]
Hint: onUnmounted cleans timers to stop background tasks [OK]
Common Mistakes:
  • Thinking count resets automatically on unmount
  • Assuming timer keeps running after unmount
  • Confusing onMounted and onUnmounted roles
4. Identify the error in this Vue 3 setup function:
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    const message = ref('Hello')

    onMounted(() => {
      console.log(message.value)
    })

    onUnmounted(() => {
      console.log('Goodbye')
    })

    onMounted(() => {
      console.log('Another mount')
    })

    return { message }
  }
}
medium
A. No error; multiple onMounted hooks are allowed and run in order
B. Multiple onMounted hooks are not allowed in the same setup
C. onUnmounted must be called before onMounted
D. message ref must be declared inside onMounted

Solution

  1. Step 1: Check Vue 3 Composition API rules for lifecycle hooks

    Vue 3 allows multiple onMounted hooks inside the same setup function; they run in the order declared.
  2. Step 2: Verify other options

    There is no requirement for onUnmounted to be before onMounted, and message can be declared outside hooks.
  3. Final Answer:

    No error; multiple onMounted hooks are allowed and run in order -> Option A
  4. Quick Check:

    Multiple onMounted hooks allowed [OK]
Hint: Multiple onMounted hooks run fine in setup [OK]
Common Mistakes:
  • Thinking only one onMounted hook is allowed
  • Believing lifecycle hooks must be in specific order
  • Assuming refs must be declared inside hooks
5. You want to create a Vue 3 component that starts a WebSocket connection when it appears and closes it when it disappears. Which is the best way to use onMounted and onUnmounted to achieve this?
import { onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    let socket

    // What should go here?

    return {}
  }
}
hard
A. Use onUnmounted to open the socket and onMounted to close it
B. Open the socket outside lifecycle hooks and close it inside onUnmounted
C. Use onMounted to open the socket and onUnmounted to close it
D. Open and close the socket both inside onMounted

Solution

  1. Step 1: Understand lifecycle timing for resource management

    Resources like WebSocket should be opened when the component appears (onMounted) and cleaned up before it disappears (onUnmounted).
  2. Step 2: Match options with correct lifecycle usage

    Use onMounted to open the socket and onUnmounted to close it correctly uses onMounted to open and onUnmounted to close the socket. Other options misuse lifecycle hooks or open/close at wrong times.
  3. Final Answer:

    Use onMounted to open the socket and onUnmounted to close it -> Option C
  4. Quick Check:

    Open onMounted, close onUnmounted for resources [OK]
Hint: Open resource onMounted, close onUnmounted [OK]
Common Mistakes:
  • Opening resource outside lifecycle hooks
  • Closing resource in onMounted instead of onUnmounted
  • Reversing open and close lifecycle hooks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard