Bird
Raised Fist0
Vueframework~10 mins

Composable with lifecycle hooks in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Composable with lifecycle hooks
Start Component Setup
↓
Call Composable Function
↓
Inside Composable: Setup Reactive State
↓
Register Lifecycle Hook (e.g., onMounted)
↓
Return State and Methods
↓
Component Uses Returned State
↓
Component Mounts
↓
Lifecycle Hook Runs
↓
Effect Happens (e.g., console log, data fetch)
↓
Component Renders with Updated State
The component calls a composable that sets up reactive state and registers lifecycle hooks. When the component mounts, the lifecycle hook inside the composable runs, triggering side effects.
Execution Sample
Vue
import { ref, onMounted } from 'vue'

function useCounter() {
  const count = ref(0)
  onMounted(() => {
    console.log('Mounted!')
  })
  return { count }
}
This composable creates a reactive count and logs 'Mounted!' when the component using it mounts.
Execution Table
StepActionState BeforeState AfterEffect
1Component setup startsNo stateNo stateNo effect
2Call useCounter composableNo statecount = 0No effect
3Register onMounted hookcount = 0count = 0Hook registered
4Composable returns { count }count = 0count = 0No effect
5Component mountscount = 0count = 0Trigger onMounted hook
6onMounted hook runscount = 0count = 0Console logs 'Mounted!'
7Component renders with count=0count = 0count = 0UI shows count 0
💡 Lifecycle hook runs once on component mount, then normal rendering continues.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6Final
countundefined0000
Key Moments - 2 Insights
Why does the console.log inside onMounted run only after the component mounts?
Because onMounted registers a hook that runs only when the component finishes mounting, as shown in step 5 and 6 of the execution_table.
Is the reactive state 'count' available before the component mounts?
Yes, 'count' is created during composable call in setup (step 2), but lifecycle hooks run later (step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'count' after step 3?
A1
Bundefined
C0
Dnull
💡 Hint
Check the 'State After' column for step 3 in execution_table.
At which step does the onMounted hook actually run?
AStep 2
BStep 6
CStep 4
DStep 7
💡 Hint
Look for the step where the effect 'Console logs "Mounted!"' happens in execution_table.
If we add a reactive variable inside onMounted instead of setup, when will it be available?
AOnly after component mounts
BImmediately during setup
CBefore component setup
DNever
💡 Hint
Recall that onMounted runs after mounting, so variables created there appear later.
Concept Snapshot
Composable with lifecycle hooks in Vue:
- Define reactive state inside composable using ref/reactive.
- Register lifecycle hooks like onMounted inside composable.
- Return state and methods from composable.
- Hooks run when component lifecycle reaches that phase.
- Enables reusable logic with side effects tied to component lifecycle.
Full Transcript
In Vue, a composable is a function that sets up reactive state and can register lifecycle hooks like onMounted. When a component calls this composable during its setup phase, the reactive state is created immediately. However, lifecycle hooks registered inside the composable only run when the component reaches that lifecycle phase, for example, when it mounts. This allows the composable to perform side effects such as logging or fetching data exactly when the component is ready. The execution table shows the step-by-step process: the component starts setup, calls the composable which creates state and registers hooks, then when the component mounts, the onMounted hook runs and triggers effects. This pattern helps organize reusable logic with lifecycle awareness.

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

  1. 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.
  2. Step 2: Connect lifecycle hooks with composables

    Using lifecycle hooks inside composables allows shared logic to run automatically when components use the composable.
  3. Final Answer:

    To run code automatically when a component starts or stops -> Option A
  4. 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

  1. Step 1: Check import syntax

    Vue lifecycle hooks like onMounted are named exports, so use curly braces in import.
  2. Step 2: Check usage syntax

    onMounted is a function that takes a callback, so call it with a function argument.
  3. Final Answer:

    import { onMounted } from 'vue'; onMounted(() => { /* code */ }); -> Option C
  4. 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?
import { ref, onMounted } from 'vue';
export function useLogger() {
  const message = ref('Hello');
  onMounted(() => {
    console.log(message.value);
  });
  return { message };
}
medium
A. Hello
B. undefined
C. null
D. An error is thrown

Solution

  1. Step 1: Understand ref initialization

    The message ref is initialized with the string 'Hello'.
  2. Step 2: Check onMounted callback

    When the component mounts, the callback logs message.value, which is 'Hello'.
  3. Final Answer:

    Hello -> Option A
  4. Quick Check:

    Ref value logged on mount = B [OK]
Hint: Ref values accessed with .value inside lifecycle hooks [OK]
Common Mistakes:
  • Logging ref without .value
  • Expecting undefined before mount
  • Thinking onMounted runs before ref initialization
4. Identify the error in this composable using lifecycle hooks:
import { onMounted, onUnmounted } from 'vue';
export function useTimer() {
  let timer = null;
  onMounted(() => {
    timer = setInterval(() => console.log('tick'), 1000);
  });
  onUnmounted(() => {
    clearInterval(timer);
  });
  return {};
}
medium
A. timer should be a ref to persist between hooks
B. onUnmounted should be onBeforeUnmount
C. setInterval callback syntax is wrong
D. No error, code works correctly

Solution

  1. Step 1: Check variable scope and usage

    Variable timer is declared in composable scope and updated in onMounted, accessible in onUnmounted.
  2. Step 2: Verify lifecycle hooks usage

    onMounted sets interval, onUnmounted clears it correctly to avoid memory leaks.
  3. Final Answer:

    No error, code works correctly -> Option D
  4. 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

  1. Step 1: Determine when to start fetch

    Fetching data should start when the component is fully mounted, so use onMounted.
  2. Step 2: Handle cleanup on unmount

    To cancel fetch if component unmounts early, use onUnmounted to abort the fetch using an AbortController.
  3. Final Answer:

    Use onMounted to start fetch and onUnmounted to abort fetch with an AbortController -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard