Bird
Raised Fist0
Vueframework~10 mins

Lifecycle hooks in Composition API in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Lifecycle hooks in Composition API
Setup function runs
↓
onBeforeMount hook
↓
Component mounts to DOM
↓
onMounted hook
↓
Reactive data changes?
↓
Component updates
↓
onBeforeUpdate hook
↓
DOM updates
↓
onUpdated hook
↓
Component unmounts
↓
onBeforeUnmount hook
↓
onUnmounted hook
↓
Cleanup done
This flow shows how Vue Composition API lifecycle hooks run in order during component setup, mounting, updating, and unmounting.
Execution Sample
Vue
import { ref, onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    const count = ref(0);
    onMounted(() => console.log('Mounted'));
    onBeforeUnmount(() => console.log('Before Unmount'));
    return { count };
  }
}
This code sets up a reactive count and logs messages when the component mounts and before it unmounts.
Execution Table
StepHook TriggeredActionConsole OutputComponent State
1setup()Initialize count=0count=0
2onMountedRun mounted callbackMountedcount=0
3Reactive changecount incremented to 1count=1
4onBeforeUpdateBefore DOM updatescount=1
5DOM updatesRender new countcount=1
6onUpdatedAfter DOM updatescount=1
7onBeforeUnmountRun before unmount callbackBefore Unmountcount=1
8onUnmountedCleanup after unmountcount=1
💡 Component unmounted, lifecycle ends
Variable Tracker
VariableStartAfter Step 3Final
count011
Key Moments - 3 Insights
Why does onMounted run after setup but before reactive changes?
Because setup initializes state first, then onMounted runs after the component is attached to the DOM but before reactive changes trigger updates, as shown in steps 1 and 2.
What happens if reactive data changes after mounting?
The onBeforeUpdate and onUpdated hooks run around the DOM update to reflect the new state, as seen in steps 3 to 6.
When do onBeforeUnmount and onUnmounted run?
They run just before and after the component is removed from the DOM, allowing cleanup, as shown in steps 7 and 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of count after step 3?
A1
Bundefined
C0
D2
💡 Hint
Check the 'Component State' column at step 3 in the execution_table.
At which step does the component first log 'Mounted'?
AStep 1
BStep 2
CStep 5
DStep 7
💡 Hint
Look at the 'Console Output' column to find when 'Mounted' appears.
If the count never changes, which hooks related to updates will NOT run?
AonMounted and onBeforeUnmount
BonBeforeUnmount and onUnmounted
ConBeforeUpdate and onUpdated
Dsetup and onMounted
💡 Hint
Refer to steps 4 and 6 where update hooks run after reactive changes.
Concept Snapshot
Vue Composition API lifecycle hooks:
- setup() runs first to initialize state
- onMounted runs after component mounts
- onBeforeUpdate and onUpdated run around reactive updates
- onBeforeUnmount and onUnmounted run during unmount
Use these hooks to run code at key component moments.
Full Transcript
This visual trace shows how Vue's Composition API lifecycle hooks work step-by-step. First, the setup function runs to create reactive data. Then onMounted runs after the component is attached to the page. When reactive data changes, onBeforeUpdate runs before the DOM updates, and onUpdated runs after. Finally, when the component is removed, onBeforeUnmount and onUnmounted run to allow cleanup. The execution table tracks these steps with state and console outputs, helping beginners see exactly when each hook triggers during the component's life.

Practice

(1/5)
1. Which lifecycle hook in Vue's Composition API runs code right after the component is added to the page?
easy
A. onUpdated
B. onCreated
C. onDestroyed
D. onMounted

Solution

  1. Step 1: Understand the lifecycle phases

    The onMounted hook runs after the component is inserted into the DOM.
  2. Step 2: Match the hook to the action

    Since the question asks for the hook that runs right after adding to the page, onMounted is the correct choice.
  3. Final Answer:

    onMounted -> Option D
  4. Quick Check:

    Mounted = after insert [OK]
Hint: Remember: mounted means component is on the page [OK]
Common Mistakes:
  • Confusing onMounted with onCreated
  • Thinking onUpdated runs after mounting
  • Using onDestroyed for setup tasks
2. Which of these is the correct way to import and use the onUnmounted hook inside the setup() function?
easy
A. import onUnmounted from 'vue';
setup() { onUnmounted(() => { /* cleanup */ }); }
B. import { onUnmounted } from 'vue';
setup() { onUnmounted(() => { /* cleanup */ }); }
C. import { onUnmounted } from 'vue';
setup() { onUnmounted = () => { /* cleanup */ }; }
D. import { onUnmounted } from 'vue';
setup() { onUnmounted; }

Solution

  1. Step 1: Check import syntax

    The correct import uses curly braces: import { onUnmounted } from 'vue';
  2. Step 2: Check usage inside setup

    The hook is called as a function with a callback: onUnmounted(() => { /* cleanup */ });
  3. Final Answer:

    Correct import and call syntax -> Option B
  4. Quick Check:

    Import with braces + call hook [OK]
Hint: Import hooks with braces and call them as functions [OK]
Common Mistakes:
  • Importing without braces
  • Assigning hook to a variable instead of calling
  • Calling hook without a callback function
3. What will be logged to the console when this Vue component runs?
import { ref, onMounted } from 'vue';
export default {
  setup() {
    const count = ref(0);
    onMounted(() => {
      count.value = 5;
      console.log('Mounted count:', count.value);
    });
    return { count };
  }
}
medium
A. Mounted count: 5
B. Mounted count: 0
C. Mounted count: undefined
D. No output

Solution

  1. Step 1: Understand ref and onMounted

    count starts at 0, then inside onMounted it is set to 5 and logged.
  2. Step 2: Predict console output

    The console logs 'Mounted count:' followed by the updated value 5.
  3. Final Answer:

    Mounted count: 5 -> Option A
  4. Quick Check:

    Value updated before log in onMounted [OK]
Hint: onMounted runs after setup, so updated values show [OK]
Common Mistakes:
  • Assuming count is still 0 inside onMounted
  • Thinking onMounted runs before setup returns
  • Confusing ref.value with ref itself
4. Identify the error in this Vue Composition API code snippet:
import { onMounted } from 'vue';
export default {
  setup() {
    onMounted = () => {
      console.log('Mounted');
    };
  }
}
medium
A. onMounted is incorrectly assigned instead of called
B. Missing import of onUnmounted
C. setup() should return a value
D. Console.log syntax is wrong

Solution

  1. Step 1: Check how onMounted is used

    The code assigns a function to onMounted instead of calling it with a callback.
  2. Step 2: Understand correct usage

    The correct usage is onMounted(() => { ... }), not assignment.
  3. Final Answer:

    onMounted is incorrectly assigned instead of called -> Option A
  4. Quick Check:

    Hooks are called, not reassigned [OK]
Hint: Use onMounted(callback), don't assign it like a variable [OK]
Common Mistakes:
  • Assigning hook instead of calling it
  • Forgetting to pass a function to onMounted
  • Thinking setup must always return something
5. You want to fetch data when a component mounts and cancel a timer when it unmounts using Composition API. Which code snippet correctly uses lifecycle hooks to do this?
hard
A.
import { ref, onUnmounted } from 'vue';
export default {
  setup() {
    const data = ref(null);
    let timer = setInterval(() => console.log('tick'), 1000);
    onUnmounted(() => {
      clearInterval(timer);
    });
    return { data };
  }
}
B.
import { ref, onMounted } from 'vue';
export default {
  setup() {
    const data = ref(null);
    onMounted(() => {
      fetch('/api/data').then(res => res.json()).then(json => data.value = json);
      setInterval(() => console.log('tick'), 1000);
    });
    return { data };
  }
}
C.
import { ref, onMounted, onUnmounted } from 'vue';
export default {
  setup() {
    const data = ref(null);
    let timer;
    onMounted(() => {
      fetch('/api/data').then(res => res.json()).then(json => data.value = json);
      timer = setInterval(() => console.log('tick'), 1000);
    });
    onUnmounted(() => {
      clearInterval(timer);
    });
    return { data };
  }
}
D.
import { ref } from 'vue';
export default {
  setup() {
    const data = ref(null);
    fetch('/api/data').then(res => res.json()).then(json => data.value = json);
    let timer = setInterval(() => console.log('tick'), 1000);
    return { data };
  }
}

Solution

  1. Step 1: Check data fetching on mount

    import { ref, onMounted, onUnmounted } from 'vue';
    export default {
      setup() {
        const data = ref(null);
        let timer;
        onMounted(() => {
          fetch('/api/data').then(res => res.json()).then(json => data.value = json);
          timer = setInterval(() => console.log('tick'), 1000);
        });
        onUnmounted(() => {
          clearInterval(timer);
        });
        return { data };
      }
    }
    uses onMounted to fetch data and start the timer, which is correct.
  2. Step 2: Check cleanup on unmount

    import { ref, onMounted, onUnmounted } from 'vue';
    export default {
      setup() {
        const data = ref(null);
        let timer;
        onMounted(() => {
          fetch('/api/data').then(res => res.json()).then(json => data.value = json);
          timer = setInterval(() => console.log('tick'), 1000);
        });
        onUnmounted(() => {
          clearInterval(timer);
        });
        return { data };
      }
    }
    uses onUnmounted to clear the timer, preventing memory leaks.
  3. Final Answer:

    Correctly uses onMounted and onUnmounted hooks -> Option C
  4. Quick Check:

    Fetch on mount + cleanup on unmount [OK]
Hint: Use onMounted for setup, onUnmounted for cleanup [OK]
Common Mistakes:
  • Starting timers outside lifecycle hooks
  • Not clearing timers on unmount
  • Fetching data outside onMounted
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