Bird
Raised Fist0
Vueframework~10 mins

State machines with composables in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - State machines with composables
Define states and transitions
↓
Create composable function
↓
Initialize current state
↓
Expose state and transition function
↓
Component uses composable
↓
User triggers event
↓
Transition function checks event
↓
Update current state if valid
↓
Component re-renders with new state
This flow shows how a Vue composable manages states and transitions in a state machine, updating the component reactively.
Execution Sample
Vue
import { ref } from 'vue';

export function useToggle() {
  const state = ref('off');
  function toggle() {
    state.value = state.value === 'off' ? 'on' : 'off';
  }
  return { state, toggle };
}
A simple composable that manages a toggle state between 'off' and 'on'.
Execution Table
StepActionCurrent State BeforeEvent TriggeredState AfterComponent Update
1Initialize composablenonenoneoffComponent shows 'off'
2User clicks toggleofftoggleonComponent updates to 'on'
3User clicks toggleontoggleoffComponent updates to 'off'
4User clicks toggleofftoggleonComponent updates to 'on'
5No eventonnoneonNo change, component stays 'on'
💡 No further events triggered, state remains stable.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
state.valueundefined'off''on''off''on''on'
Key Moments - 3 Insights
Why does the component update when state.value changes?
Because state is a Vue ref, changes to state.value trigger reactive updates causing the component to re-render, as shown in steps 2, 3, and 4 in the execution_table.
What happens if an invalid event is triggered?
In this simple toggle example, only the 'toggle' event changes state. If no event or an unknown event occurs, the state stays the same, as shown in step 5.
Why do we use a composable for state machines?
Composables encapsulate state logic and transitions, making it reusable and clean. This separation helps components stay simple and focused on UI.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state after step 3?
A'on'
B'undefined'
C'off'
D'toggle'
💡 Hint
Check the 'State After' column in row with Step 3.
At which step does the component first show 'on'?
AStep 1
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Component Update' column for when it changes to 'on'.
If the toggle function was never called, what would the final state be according to variable_tracker?
A'off'
B'on'
C'undefined'
DNo state
💡 Hint
Check the 'Start' and 'After 1' values in variable_tracker for state.value.
Concept Snapshot
State machines with composables in Vue:
- Define states and transitions inside a composable function.
- Use Vue's ref to hold current state reactively.
- Expose state and transition functions to components.
- Components reactively update when state changes.
- Composables keep logic reusable and clean.
Full Transcript
This visual execution shows how to build a simple state machine using Vue composables. We start by defining states and transitions inside a composable function. The current state is stored in a reactive ref. When the user triggers an event, the transition function updates the state if valid. This change causes the component to re-render and show the new state. The execution table traces each step: initialization, user toggles, and state updates. The variable tracker shows how the state variable changes over time. Key moments clarify why reactive refs cause updates and why composables help organize state logic. The quiz tests understanding of state changes and component updates. This approach helps beginners see how state machines work in Vue with composables.

Practice

(1/5)
1. What is the main purpose of using a state machine in a Vue composable?
easy
A. To manage and control the different states of an application clearly and predictably
B. To style components dynamically based on user input
C. To fetch data from an API asynchronously
D. To create reusable UI components without state

Solution

  1. Step 1: Understand state machine role

    A state machine helps track and control states in a clear way, avoiding unpredictable behavior.
  2. Step 2: Relate to Vue composables

    Vue composables organize this logic so it can be reused across components easily.
  3. Final Answer:

    To manage and control the different states of an application clearly and predictably -> Option A
  4. Quick Check:

    State machine purpose = Manage states clearly [OK]
Hint: State machines organize app states clearly, not styling or fetching [OK]
Common Mistakes:
  • Confusing state machines with styling or data fetching
  • Thinking composables only create UI components
  • Assuming state machines handle API calls
2. Which of the following is the correct way to declare a reactive state variable for a state machine in a Vue composable?
easy
A. const state = reactive('idle')
B. const state = ref('idle')
C. const state = computed('idle')
D. const state = watch('idle')

Solution

  1. Step 1: Identify reactive state declaration

    In Vue composables, ref is used to create a reactive primitive value like a string.
  2. Step 2: Check other options

    reactive is for objects, computed is for derived values, and watch is for side effects, so they are incorrect here.
  3. Final Answer:

    const state = ref('idle') -> Option B
  4. Quick Check:

    Use ref for reactive primitives [OK]
Hint: Use ref() for reactive simple values like strings [OK]
Common Mistakes:
  • Using reactive() for primitive values
  • Confusing computed() with state declaration
  • Using watch() to declare state
3. Given this Vue composable code, what will be the value of state.value after calling next() twice?
import { ref } from 'vue'

export function useMachine() {
  const state = ref('idle')
  function next() {
    if (state.value === 'idle') state.value = 'loading'
    else if (state.value === 'loading') state.value = 'success'
  }
  return { state, next }
}
medium
A. 'idle'
B. 'loading'
C. 'success'
D. undefined

Solution

  1. Step 1: Trace first next() call

    Initial state is 'idle'. Calling next() changes it to 'loading'.
  2. Step 2: Trace second next() call

    Now state is 'loading'. Calling next() again changes it to 'success'.
  3. Final Answer:

    'success' -> Option C
  4. Quick Check:

    Two next() calls move state from idle -> loading -> success [OK]
Hint: Trace state changes step-by-step for each next() call [OK]
Common Mistakes:
  • Assuming state resets to 'idle'
  • Forgetting second next() changes state again
  • Confusing state.value with state itself
4. Identify the error in this Vue composable state machine code:
import { ref } from 'vue'

export function useMachine() {
  const state = ref('idle')
  function next() {
    if (state === 'idle') state.value = 'loading'
    else if (state.value === 'loading') state.value = 'success'
  }
  return { state, next }
}
medium
A. next() function is not returned
B. Missing import of ref from 'vue'
C. Cannot assign to state.value, should assign to state
D. Incorrect comparison: should use state.value instead of state

Solution

  1. Step 1: Check state comparisons

    state is a ref object, so to compare its value, use state.value, not state directly.
  2. Step 2: Verify other parts

    Import is correct, assignment to state.value is correct, and next() is returned properly.
  3. Final Answer:

    Incorrect comparison: should use state.value instead of state -> Option D
  4. Quick Check:

    Compare ref values with state.value [OK]
Hint: Always compare ref values with .value, not the ref object [OK]
Common Mistakes:
  • Comparing ref object instead of its value
  • Forgetting to return functions from composable
  • Misassigning to ref object instead of .value
5. You want to extend a Vue composable state machine to handle a 'failure' state after 'loading'. Which change correctly adds this new state transition when next() is called from 'loading'?
hard
A. Add an else if: else if (state.value === 'loading') state.value = 'failure'
B. Replace the existing loading transition with state.value = 'failure' only
C. Add a new function to set state to 'failure' instead of modifying next()
D. Change initial state to 'failure' to handle errors

Solution

  1. Step 1: Understand current transitions

    Currently, next() changes 'idle' -> 'loading' -> 'success'. To handle 'failure' after 'loading' when next() is called, add a new else if condition for 'loading' to transition to 'failure'.
  2. Step 2: Identify correct addition

    Adding an else if for state.value === 'loading' to set state.value = 'failure' extends the state machine correctly without removing existing transitions.
  3. Final Answer:

    Add an else if: else if (state.value === 'loading') state.value = 'failure' -> Option A
  4. Quick Check:

    Add new transition for loading -> failure without removing others [OK]
Hint: Add a new else if condition for the failure state [OK]
Common Mistakes:
  • Adding a duplicate else if for 'loading' which conflicts or is unreachable
  • Adding separate functions instead of modifying next()
  • Changing initial state instead of the transition
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