Updating State and Reactivity Details

Explore direct state updates, $patch, $reset, and considerations for reactive objects and arrays in Pinia.

🎯 Introduction

By the end of this article, you will know three ways to update Pinia state and when to use each. You will also learn about reactivity pitfalls when working with objects and arrays to make state management more reliable.


✨ Direct Updates: The Simplest Approach

Pinia allows direct state updates, one of its biggest differences from Vuex.

stores/counter.js
export const useCounterStore = defineStore('counter', {
    state: () => ({
        count: 0,
    }),
});

In a component:

<template>
    <p>{{ counter.count }}</p>
    <button @click="counter.count++">Add 1</button>
    <button @click="counter.count = 0">Reset</button>
</template>
Direct assignment is the clearest approach for a single property. For updates involving many properties or complex logic, consider $patch or an action.

🛠 $patch: Updating Multiple Properties

Use $patch to make updates to several state properties clearer:

counter.$patch({
    count: 10,
    name: 'Taylor',
});

$patch also accepts a function, which is useful when updates depend on the current state:

counter.$patch((state) => {
    state.count++;
});
The function form of $patch receives the current state as its argument, allowing you to modify it directly. This keeps related logic together and makes changes easier to track.

🔄 $reset: Restoring Initial Values

Call $reset to restore the initial values defined in the state() function:

counter.$reset(); // count returns to 0
$reset only applies to the initial state defined through state: () => ({}). If you previously replaced an entire object property with $patch, the reset behavior may differ from what you expect.

⚡ Reactivity Pitfalls with Objects and Arrays

Replacing an Entire Object

The following approach breaks reactivity:

const user = useUserStore();
user.info = { name: 'Taylor', age: 25 }; // ❌ May lose reactivity

Why? Replacing the entire info reference can interfere with Pinia’s reactive tracking of that property.

The recommended approach:

// ✅ Update individual properties
user.info.name = 'Taylor';
user.info.age = 25;

// ✅ Or use $patch
user.$patch({
    info: { name: 'Taylor', age: 25 },
});

Array Operations

Array methods such as push and splice preserve reactivity:

const list = useListStore();

list.items.push('New item'); // ✅
list.items.splice(0, 1); // ✅

Be careful when replacing an entire object through an array index:

list.items[0] = { id: 2, name: 'New' }; // ⚠️ May not trigger an update

A safer approach:

list.$patch((state) => {
    state.items[0] = { id: 2, name: 'New' };
});
Although Pinia state is reactive, certain assignments to JavaScript objects and arrays can break reactive tracking. When unsure, prefer $patch.

💡 Choosing Between Three Update Approaches

ApproachWhen to use itExample
Direct updatesSimple assignment to a single propertycounter.count++
$patchBatch updates or complex object/array operationscounter.$patch({...})
ActionsComplex or reusable business logiccounter.add()

❓ Questions and Answers

Q1: Are direct updates or $patch better?

Neither is always better. Direct updates are more concise for one property; $patch is clearer for multiple properties or complex operations.

Q2: Can $reset reset state changed by an action?

Yes. $reset restores the initial values returned by state(), regardless of how they were changed.

Q3: Why does replacing an entire object lose reactivity?

The reactivity system tracks object references. Replacing a reference with a new plain object disconnects the original reactive proxy.

Q4: Does assigning an array element by index always fail?

Not always, but its behavior is less reliable than push/splice/$patch. Prefer the safer approaches to avoid pitfalls.


🧪 Exercise

Complete the following usePointStore with:

  1. A points property initialized to 0.
  2. An add(n) action that increases points by n.
  3. A consume(n) action that spends points only when enough points are available.
  4. A reset() action that resets points to 0.
stores/point.js
import { defineStore } from 'pinia';

export const usePointStore = defineStore('point', {
    state: () => ({
        points: 0,
    }),
    actions: {
        // Write your code here
    },
});

🎉 You now know the different ways to update state! Next, we will handle asynchronous requests in actions.