Bird
Raised Fist0
Vueframework~10 mins

Creating a custom composable in Vue - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - Creating a custom composable
Define composable function
↓
Inside: create reactive state
↓
Inside: define functions to update state
↓
Return state and functions
↓
Use composable in component
↓
Component reacts to state changes
This flow shows how to create a composable function that holds reactive state and functions, then use it inside a Vue component to share logic.
Execution Sample
Vue
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}
Defines a composable that creates a reactive count and an increment function to update it.
Execution Table
StepActionState BeforeState AfterOutput/Effect
1Call useCounter()No countcount = 0Composable returns count and increment
2Call increment()count = 0count = 1count reactive value updated
3Call increment()count = 1count = 2count reactive value updated
4Component reads countcount = 2count = 2Component shows count = 2
5No more actionscount = 2count = 2Execution ends
💡 No more actions; composable usage complete
Variable Tracker
VariableStartAfter 1After 2Final
count.valueundefined012
Key Moments - 3 Insights
Why do we use ref() inside the composable?
ref() creates a reactive variable so Vue tracks changes and updates the component automatically, as shown in execution_table steps 1 and 2.
What happens when increment() is called multiple times?
Each call increases count.value by 1, updating the reactive state and causing the component to re-render, as seen in steps 2 and 3.
Why do we return count and increment from the composable?
Returning them allows components to access the reactive state and functions, enabling shared logic and reactivity, demonstrated in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is count.value after the second increment call?
A2
B1
C0
DUndefined
💡 Hint
Check execution_table row 3 where increment() updates count.value to 2
At which step does the component first display the count value?
AStep 1
BStep 4
CStep 2
DStep 5
💡 Hint
Look at execution_table row 4 where component reads count to display
If we did not use ref() for count, what would happen?
Acount would still be reactive
Bincrement() would not work
Ccount would not update the component automatically
DThe composable would throw an error
💡 Hint
Recall key_moments about ref() creating reactive variables
Concept Snapshot
Creating a custom composable:
- Define a function starting with 'use'
- Inside, create reactive state with ref() or reactive()
- Define functions to update state
- Return state and functions
- Use composable in components to share reactive logic
Full Transcript
This visual trace shows how to create a custom composable in Vue. First, we define a function called useCounter that creates a reactive variable count using ref(0). We also define an increment function that increases count.value by one. The composable returns both count and increment. When the composable is used in a component, calling increment updates count.value, which triggers the component to re-render and show the new count. The execution table tracks each step: calling useCounter initializes count to 0, calling increment updates count to 1 and then 2, and the component reads count to display it. Key moments clarify why ref() is needed for reactivity, how increment updates state, and why returning state and functions is important. The quiz tests understanding of count's value changes, when the component displays count, and the role of ref(). This helps beginners see how composables share reactive logic cleanly in Vue.

Practice

(1/5)
1. What is the main purpose of creating a custom composable in Vue?
easy
A. To define global CSS styles
B. To reuse reactive logic across multiple components
C. To create new Vue directives
D. To register components globally

Solution

  1. Step 1: Understand what composables do

    Custom composables are functions that encapsulate reactive logic to be reused.
  2. Step 2: Identify the purpose in Vue components

    They help share logic without repeating code in multiple components.
  3. Final Answer:

    To reuse reactive logic across multiple components -> Option B
  4. Quick Check:

    Reusable reactive logic = B [OK]
Hint: Composables = reusable reactive logic functions [OK]
Common Mistakes:
  • Confusing composables with styling or directives
  • Thinking composables register components
  • Assuming composables handle templates
2. Which of the following is the correct way to start a custom composable function in Vue 3?
easy
A. function useData() { const count = ref(0); return { count }; }
B. const useData = () => { const count = reactive(0); return count; }
C. function useData() { const count = ref(0); }
D. const useData = () => { return ref({ count: 0 }); }

Solution

  1. Step 1: Check function declaration and return

    function useData() { const count = ref(0); return { count }; } declares a function named with 'use' prefix and returns reactive refs.
  2. Step 2: Validate reactive usage and return object

    function useData() { const count = ref(0); return { count }; } returns an object with the reactive ref, which is correct pattern.
  3. Final Answer:

    function useData() { const count = ref(0); return { count }; } -> Option A
  4. Quick Check:

    Composable returns reactive refs in object = D [OK]
Hint: Composable must return reactive data inside an object [OK]
Common Mistakes:
  • Not returning reactive data
  • Returning reactive primitive directly instead of object
  • Missing 'use' prefix in function name
3. Given this composable code, what will be logged when calling increment() twice?
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
    console.log(count.value);
  }
  return { count, increment };
}
medium
A. Undefined and then 1
B. 0 and then 1
C. 2 and then 3
D. 1 and then 2

Solution

  1. Step 1: Understand initial count value

    The count starts at 0 as a ref.
  2. Step 2: Trace increment calls and console logs

    Each increment increases count.value by 1 and logs it immediately.
  3. Final Answer:

    1 and then 2 -> Option D
  4. Quick Check:

    Increment twice logs 1 then 2 [OK]
Hint: Ref value increments and logs immediately [OK]
Common Mistakes:
  • Confusing ref.value with ref itself
  • Assuming count starts at 1
  • Thinking console logs before increment
4. Identify the error in this composable code:
import { ref } from 'vue';

export function useToggle() {
  const state = ref(false);
  function toggle() {
    state = !state;
  }
  return { state, toggle };
}
medium
A. ref should be reactive instead
B. Missing return statement
C. Cannot reassign a const ref variable directly
D. toggle function should be async

Solution

  1. Step 1: Check how ref is updated

    The code tries to assign 'state = !state', which reassigns the const variable.
  2. Step 2: Correct way to update ref value

    Should update 'state.value = !state.value' instead of reassigning 'state'.
  3. Final Answer:

    Cannot reassign a const ref variable directly -> Option C
  4. Quick Check:

    Update ref.value, not ref variable [OK]
Hint: Update ref.value, never reassign ref variable [OK]
Common Mistakes:
  • Reassigning ref variable instead of its value
  • Forgetting to use .value to access ref
  • Assuming reactive is needed instead of ref
5. You want to create a composable that fetches user data and exposes loading state. Which approach correctly combines reactive state and async fetch inside a composable?
hard
A. function useUser() { const user = ref(null); const loading = ref(true); async function fetchUser() { loading.value = true; user.value = await fetch('/api/user').then(r => r.json()); loading.value = false; } fetchUser(); return { user, loading }; }
B. function useUser() { const user = reactive(null); const loading = false; async function fetchUser() { loading = true; user = await fetch('/api/user').then(r => r.json()); loading = false; } fetchUser(); return { user, loading }; }
C. function useUser() { const user = ref(null); const loading = ref(false); function fetchUser() { loading.value = true; fetch('/api/user').then(r => r.json()).then(data => { user.value = data; loading.value = false; }); } return { user, loading, fetchUser }; }
D. function useUser() { const user = ref(null); const loading = ref(true); fetch('/api/user').then(r => r.json()).then(data => { user = data; loading.value = false; }); return { user, loading }; }

Solution

  1. Step 1: Check reactive state initialization

    function useUser() { const user = ref(null); const loading = ref(true); async function fetchUser() { loading.value = true; user.value = await fetch('/api/user').then(r => r.json()); loading.value = false; } fetchUser(); return { user, loading }; } correctly uses ref for user and loading states.
  2. Step 2: Verify async fetch and state updates

    function useUser() { const user = ref(null); const loading = ref(true); async function fetchUser() { loading.value = true; user.value = await fetch('/api/user').then(r => r.json()); loading.value = false; } fetchUser(); return { user, loading }; } uses async function to set loading true, await fetch, then set loading false.
  3. Step 3: Confirm fetch is called inside composable

    function useUser() { const user = ref(null); const loading = ref(true); async function fetchUser() { loading.value = true; user.value = await fetch('/api/user').then(r => r.json()); loading.value = false; } fetchUser(); return { user, loading }; } calls fetchUser() immediately to start loading data.
  4. Final Answer:

    function useUser() { const user = ref(null); const loading = ref(true); async function fetchUser() { loading.value = true; user.value = await fetch('/api/user').then(r => r.json()); loading.value = false; } fetchUser(); return { user, loading }; } -> Option A
  5. Quick Check:

    Async fetch with reactive refs = A [OK]
Hint: Use ref for state and async function with await inside composable [OK]
Common Mistakes:
  • Reassigning reactive or ref variables directly
  • Not using async/await properly
  • Not updating loading state correctly
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