Bird
Raised Fist0
Vueframework~10 mins

Defining state in stores in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Defining state in stores
Create store file
↓
Define state object
↓
Export store function
↓
Use store in component
↓
Access reactive state
↓
Update state triggers UI update
This flow shows how you create a store by defining state, export it, use it in components, and how state changes update the UI.
Execution Sample
Vue
import { reactive } from 'vue'

export const useCounterStore = () => {
  const state = reactive({ count: 0 })
  return { state }
}
Defines a simple store with a reactive state object holding a count starting at 0.
Execution Table
StepActionState BeforeState AfterEffect
1Import reactive from VueN/AN/AReady to create reactive state
2Define state = reactive({ count: 0 })N/A{ count: 0 }State object created with count 0
3Return { state } from store function{ count: 0 }{ count: 0 }Store exposes reactive state
4Component calls useCounterStore()N/A{ count: 0 }Component gets reactive state
5Component reads state.count{ count: 0 }{ count: 0 }UI shows count 0
6Component updates state.count = 1{ count: 0 }{ count: 1 }UI updates to show count 1
7Component updates state.count = 5{ count: 1 }{ count: 5 }UI updates to show count 5
8Component unmounts or store discarded{ count: 5 }N/AState no longer used
💡 Store usage ends when component unmounts or store is no longer referenced.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6After Step 7Final
state.countN/A0015N/A
Key Moments - 3 Insights
Why do we use reactive() to define state instead of a plain object?
Using reactive() makes the state reactive, so Vue tracks changes and updates the UI automatically, as shown in steps 2 and 6 of the execution_table.
What happens if we change state.count directly in the component?
Changing state.count directly updates the reactive state and triggers UI updates, as seen in steps 6 and 7 where the UI reflects new count values.
Why do we return the state object from the store function?
Returning the state object allows components to access and reactively use the shared state, demonstrated in step 3 and 4 where the component receives the reactive state.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2. What is the value of state.count after defining the reactive state?
Anull
Bundefined
C0
D1
💡 Hint
Check the 'State After' column in step 2 of the execution_table.
At which step does the UI first update to show count = 1?
AStep 6
BStep 5
CStep 4
DStep 7
💡 Hint
Look for the step where state.count changes from 0 to 1 and UI updates.
If we did not use reactive() and used a plain object for state, what would happen?
AUI would update normally
BState changes would not trigger UI updates
CCode would throw an error
DState would be immutable
💡 Hint
Refer to the key_moments explanation about reactive() usage.
Concept Snapshot
Defining state in stores in Vue:
- Use reactive() to create reactive state objects.
- Export a function returning the state.
- Components call this function to access shared reactive state.
- Changing state properties updates the UI automatically.
- This pattern centralizes state for easy reuse and reactivity.
Full Transcript
This visual execution trace shows how to define state in Vue stores using reactive(). First, reactive is imported from Vue. Then, a state object is created with reactive({ count: 0 }), making count reactive. The store function returns this state object. When a component calls the store function, it receives the reactive state. Reading state.count shows 0 initially. Updating state.count to 1 or 5 triggers UI updates reflecting these values. The reactive wrapper ensures Vue tracks changes and updates the UI automatically. This pattern helps share and manage state across components efficiently.

Practice

(1/5)
1. What is the correct way to define the state in a Vue store using defineStore?
easy
A. Define state as an array of values.
B. Define state as a plain object directly.
C. Define state as a function that returns an object.
D. Define state as a string representing JSON.

Solution

  1. Step 1: Understand Vue store state definition

    Vue stores require state to be a function returning an object to avoid shared state across instances.
  2. Step 2: Compare options with Vue pattern

    Only defining state as a function returning an object matches Vue's recommended pattern.
  3. Final Answer:

    Define state as a function that returns an object. -> Option C
  4. Quick Check:

    State = function returning object [OK]
Hint: State must be a function returning an object in Vue stores [OK]
Common Mistakes:
  • Defining state as a plain object causes shared state bugs
  • Using arrays or strings instead of objects for state
  • Forgetting to return the object from the state function
2. Which of the following is the correct syntax to define a store named 'user' with a state containing a 'name' property initialized to an empty string?
easy
A. const useUserStore = defineStore({ id: 'user', state: () => ({ name: '' }) })
B. const useUserStore = defineStore('user', { state: { name: '' } })
C. const useUserStore = defineStore('user', () => ({ name: '' }))
D. const useUserStore = defineStore('user', { state: () => ({ name: '' }) })

Solution

  1. Step 1: Recall defineStore syntax

    The first argument is the store id string, the second is an object with a state function returning the state object.
  2. Step 2: Check each option

    const useUserStore = defineStore('user', { state: () => ({ name: '' }) }) correctly uses defineStore with id 'user' and state as a function returning { name: '' }.
  3. Final Answer:

    const useUserStore = defineStore('user', { state: () => ({ name: '' }) }) -> Option D
  4. Quick Check:

    defineStore(id, { state: () => ({}) }) [OK]
Hint: Use defineStore('id', { state: () => ({}) }) syntax [OK]
Common Mistakes:
  • Defining state as an object instead of a function
  • Passing state function as the second argument directly
  • Using an object with 'id' property instead of string id
3. Given the following store definition, what will be the initial value of store.count after calling const store = useCounterStore()?
const useCounterStore = defineStore('counter', {
  state: () => ({ count: 10 })
})
medium
A. 10
B. 0
C. null
D. undefined

Solution

  1. Step 1: Analyze the state function

    The state function returns an object with count initialized to 10.
  2. Step 2: Understand store instance value

    When useCounterStore() is called, it creates a store instance with count set to 10 as initial state.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Initial count = 10 [OK]
Hint: State function returns initial values used in store instance [OK]
Common Mistakes:
  • Assuming count defaults to 0 if not explicitly set
  • Confusing state function with plain object
  • Expecting undefined because of missing initialization
4. Identify the error in this store definition:
const useTodoStore = defineStore('todo', {
  state: {
    todos: []
  }
})
medium
A. The todos array should be initialized outside the state.
B. State must be a function returning an object, not an object directly.
C. The store id 'todo' must be an object, not a string.
D. The defineStore function requires no arguments.

Solution

  1. Step 1: Check state definition format

    State must be a function returning an object to avoid shared state across instances.
  2. Step 2: Identify the error

    The code defines state as an object directly, which is incorrect.
  3. Final Answer:

    State must be a function returning an object, not an object directly. -> Option B
  4. Quick Check:

    State = function returning object, not plain object [OK]
Hint: State must always be a function returning an object [OK]
Common Mistakes:
  • Defining state as a plain object causes shared state bugs
  • Misunderstanding store id type requirements
  • Incorrect usage of defineStore arguments
5. You want to create a store that holds a list of users and a method to add a new user. Which is the correct way to define the state and actions in defineStore?
hard
A. defineStore('users', { state: () => ({ users: [] }), actions: { addUser(user) { this.users.push(user) } } })
B. defineStore('users', { state: { users: [] }, methods: { addUser(user) { this.users.push(user) } } })
C. defineStore('users', () => ({ users: [], addUser(user) { this.users.push(user) } }))
D. defineStore('users', { state: () => ({ users: [] }), addUser(user) { this.users.push(user) } })

Solution

  1. Step 1: Define state as a function returning an object

    The state must be a function returning an object with users array.
  2. Step 2: Define actions inside the actions property

    Actions are methods inside the actions object to modify state safely.
  3. Step 3: Verify correct syntax

    defineStore('users', { state: () => ({ users: [] }), actions: { addUser(user) { this.users.push(user) } } }) correctly defines state as a function and actions as an object with addUser method.
  4. Final Answer:

    defineStore('users', { state: () => ({ users: [] }), actions: { addUser(user) { this.users.push(user) } } }) -> Option A
  5. Quick Check:

    State function + actions object = correct store [OK]
Hint: Put actions inside 'actions' object, state as function [OK]
Common Mistakes:
  • Defining state as an object instead of a function
  • Placing methods outside the actions property
  • Using 'methods' instead of 'actions' in defineStore
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