| | |

Pinia 02 ๐Ÿ Defining Stores (Option vs. Setup) โ€” Choosing between Options-style and Composition API Setup stores

โฑ๏ธ Estimated read: 11 min | |

Defining a store is the foundational act of state management in Pinia. A store is a standalone entity that holds state, computed properties (getters), and methods (actions). Unlike the monolithic structure of its predecessor, Pinia encourages developers to create multiple, specific stores that handle distinct domains of the application, such as an AuthStore, a CartStore, or a UserPreferencesStore. This modularity is made possible by the defineStore function, which acts as the factory for creating these reactive data containers.

One of Piniaโ€™s most powerful features is its flexibility in syntax. It offers two distinct ways to define a store: the Option Store and the Setup Store. The Option Store follows a structure familiar to those who have used the Vue Options API or Vuex, utilizing an object with predefined keys for state, getters, and actions. The Setup Store, on the other hand, embraces the Vue 3 Composition API, allowing you to define state using ref(), getters using computed(), and actions as standard functions.

Choosing between these two patterns is not just a matter of aesthetic preference; it impacts how you write logic, how TypeScript infers your types, and how the store interacts with advanced Vue features like watchers or provide/inject. While both patterns are functionally equivalent in most scenarios, understanding the nuances of each is essential for building a scalable and maintainable architecture.

This chapter provides an in-depth exploration of both store definitions. We will dissect the syntax of Option Stores and Setup Stores, compare their reactivity models, and provide a decision framework to help you choose the right approach for your project. We will also cover the critical concept of “Store IDs” and how Pinia uses them to manage its internal registry.

Key point: Option Stores use an object-based configuration (state, getters, actions), while Setup Stores use a function-based approach (refs, computed, functions), mirroring the split between Vue’s Options API and Composition API.


Why exists

The Familiarity problem.
Many developers transitioning to Pinia come from Vue 2 or Vuex backgrounds. For these developers, an object-based structure where data, computed properties, and methods are strictly separated is intuitive and reduces the learning curve. Option Stores exist to provide this familiar structure, making the migration path smoother and the code more predictable for teams used to traditional Vue patterns.

The Logic Complexity problem.
As stores grow, they often need more than just simple data storage. They might require complex side effects, internal watchers, or the ability to inject global properties. Setup Stores exist to provide the full power of the Composition API within the store context. By using a function instead of an object, developers can use any composable or Vue reactivity tool (like watch or onUnmounted) directly inside the store.

The TypeScript Inference problem.
In older state management systems, getting TypeScript to understand the relationship between state and actions was a manual and error-prone process. Both store patterns in Pinia exist to automate this. Option Stores use “this” context mapping, while Setup Stores rely on standard variable inference. This ensures that when you call an action, the IDE knows exactly what parameters it expects and what the state looks like.

The SSR (Server-Side Rendering) problem.
In a server environment, state must be isolated between different requests to prevent data leakage. Option Stores enforce a “state as a function” pattern to ensure a fresh state instance is created for every user. Setup Stores achieve this naturally through their function scope. Both exists to make Vue applications “Universal” or “Isomorphic” by default.

The Debugging and Tooling problem.
State management can become a “black box” if not properly exposed to devtools. Pinia exists to provide a uniform interface for the Vue DevTools regardless of how the store was defined. By requiring a unique id for every store, Pinia can map both Option and Setup stores into the same visual timeline, allowing developers to inspect state changes and trigger actions with ease.


a. Option Stores: The Structured Approach

Option Stores are defined by passing an object as the second argument to defineStore. This object has three main properties: state, getters, and actions. This structure forces a clean separation of concerns, which can be beneficial for larger teams or less experienced developers who might otherwise write disorganized logic.

import { defineStore } from 'pinia';

// The first argument is a unique ID (name) for the store
export const useCounterStore = defineStore('counter', {
  // State: The data (must be a function)
  state: () => ({
    count: 0,
    name: 'Eduardo',
  }),

  // Getters: Computed values based on state
  getters: {
    // Automatically receives 'state' as the first argument
    doubleCount: (state) => state.count * 2,
    // Can also use 'this' to access other getters
    doublePlusOne(): number {
      return this.doubleCount + 1;
    },
  },

  // Actions: Methods that change state or perform side effects
  actions: {
    increment() {
      // In Option Stores, you access state via 'this'
      this.count++;
    },
    async fetchRemoteValue() {
      const val = await api.get('/count');
      this.count = val;
    },
  },
});

The state must be a function that returns an object. This is a strict requirement to prevent state sharing across server requests in SSR environments. getters are the computed properties of the store; they are cached and only re-evaluate when their dependencies change. actions are the functions that contain business logic. Unlike Vuex, there is no separate “mutations” conceptโ€”actions can and should modify the state directly using this.


b. Setup Stores: The Functional Approach

Setup Stores are defined by passing a function as the second argument to defineStore. This function works exactly like the setup() hook in a Vue component. You define your state as refs, your getters as computed properties, and your actions as plain functions.

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useCounterStore = defineStore('counter', () => {
  // State: defined as refs or reactives
  const count = ref(0);
  const name = ref('Eduardo');

  // Getters: defined as computed properties
  const doubleCount = computed(() => count.value * 2);

  // Actions: defined as standard functions
  function increment() {
    count.value++;
  }

  // CRITICAL: You must return everything the store exposes
  return { count, name, doubleCount, increment };
});

In Setup Stores, the relationship between the different parts is explicit. You don’t use this to access data; instead, you interact with the variables defined in the function scope. This approach is often preferred when the store logic is complex or when you want to use other composables (like a useLocalStorage hook) inside your store. It feels more “native” to the Vue 3 ecosystem and allows for more flexible code organization.


c. Comparative Analysis and Selection

Choosing between the two depends on the specific needs of your project and your team’s familiarity with the Composition API.

When to use Option Stores:

  • You prefer a strict, opinionated structure.
  • You are migrating from Vuex and want a similar mental model.
  • You want to use the $reset() method (which is built-in for Option stores but must be manually implemented in Setup stores).
  • Your store logic is simple and doesn’t require complex watchers or external composables.

When to use Setup Stores:

  • You are comfortable with the Composition API and prefer its flexibility.
  • You need to use watch() or provide/inject within the store.
  • You want to use other composables inside your store (e.g., useRoute() or useWindowSize()).
  • You find the this context in JavaScript confusing or want to avoid it for better static analysis.

One technical distinction is the $reset() method. Because Option Stores have a separate state function, Pinia can easily call that function to revert the state to its original values. In Setup Stores, Pinia doesn’t know which ref corresponds to what initial value, so if you need a reset functionality, you have to write it yourself within the return object.


Complete Example Session

// ============================================
// PART 1: OPTION STORE - STATE DEFINITION
// ============================================
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    firstName: 'John',
    lastName: 'Doe',
    age: 25,
    items: [] as string[]
  }),

// ============================================
// PART 2: OPTION STORE - GETTERS
// ============================================
  getters: {
    fullName: (state) => `${state.firstName} ${state.lastName}`,
    isAdult: (state) => state.age >= 18
  },

// ============================================
// PART 3: OPTION STORE - ACTIONS
// ============================================
  actions: {
    birthday() {
      this.age++; // Direct mutation via 'this'
    },
    addItem(item: string) {
      this.items.push(item);
    }
  }
});

// ============================================
// PART 4: SETUP STORE - REFS (STATE)
// ============================================
import { ref, computed, watch } from 'vue';

export const useSettingsStore = defineStore('settings', () => {
  const theme = ref('light');
  const fontSize = ref(14);

// ============================================
// PART 5: SETUP STORE - COMPUTED (GETTERS)
// ============================================
  const isDark = computed(() => theme.value === 'dark');

// ============================================
// PART 6: SETUP STORE - FUNCTIONS (ACTIONS)
// ============================================
  function toggleTheme() {
    theme.value = theme.value === 'light' ? 'dark' : 'light';
  }

// ============================================
// PART 7: SETUP STORE - ADVANCED (WATCHERS)
// ============================================
  watch(theme, (newTheme) => {
    localStorage.setItem('app-theme', newTheme);
  });

// ============================================
// PART 8: SETUP STORE - RETURN
// ============================================
  return { theme, fontSize, isDark, toggleTheme };
});

// ============================================
// PART 9: USING BOTH IN A COMPONENT
// ============================================
/*
<script setup>
const user = useUserStore();
const settings = useSettingsStore();

user.birthday();
settings.toggleTheme();
</script>
*/

// ============================================
// PART 10: RESETTING OPTION STORE
// ============================================
// user.$reset(); // Automatically works for user store

The parts above contrast the definition of state, getters, and actions in both styles, highlighting the use of this in Option stores and the use of Vue-native functions like watch in Setup stores.


Quick Reference

Syntax Comparison

FeatureOption StoreSetup Store
Statestate: () => ({ ... })const x = ref(...)
Gettersgetters: { name: (state) => ... }const name = computed(...)
Actionsactions: { method() { ... } }function method() { ... }
ReactivityAutomatic wrappingExplicit ref/reactive
Resetstore.$reset() (Native)Manual implementation required
Accessing LogicUsing thisUsing variables in scope

defineStore Signature

ArgumentTypeDescription
idStringUnique identifier (required)
setupObject OR FunctionThe logic of the store

Best Practices

โœ… Do This:

// Use Option Stores for standard data storage and simple logic
export const useDataStore = defineStore('data', { ... });       // โœ…

// Use Setup Stores when you need internal watchers or composables
export const useAuthStore = defineStore('auth', () => { ... }); // โœ…

// Always return every piece of state/action in Setup Stores
return { stateRef, actionFunc };                               // โœ…

// Keep the store ID unique across the entire application
defineStore('unique-id-here', { ... });                        // โœ…

โŒ Don’t Do This:

// Don't mix 'this' and refs inside the same store
// (Pinia doesn't support hybrid definitions)                  // โŒ

// Don't forget to export the store hook
const useStore = defineStore(...); // Missing 'export'         // โŒ

// Don't use arrow functions for actions in Option Stores
// (Arrow functions break the 'this' binding)                  // โŒ

// Don't define state as a plain object in Option Stores
state: { count: 0 } // Should be state: () => ({ count: 0 })   // โŒ

Common Pitfalls

PitfallWhy It HappensFix
this is undefinedUsed arrow function for an action in Option StoreUse standard function syntax increment() { ... }
$reset() is not a functionAttempted to call $reset() on a Setup StoreManually implement a reset function in the return object
Missing propertiesProperty was defined in Setup Store but not returnedEnsure all exposed refs/functions are in the return block
Duplicate ID ErrorTwo stores share the same string identifierAssign a unique name to every defineStore call
Reactivity LossDestructuring state without storeToRefsAccess via store.property or use storeToRefs
Infinite LoopAction updates state that a watcher is observingUse a guard or if condition inside the watcher

Real-World Examples

1. Option Store with Computed Getter

getters: { double: (state) => state.val * 2 }

2. Option Store with Cross-Getter Access

getters: { triple(): number { return this.double + this.val } }

3. Setup Store using Local Storage Composable

const token = useLocalStorage('token', null);

4. Setup Store with Internal Watcher

watch(count, (v) => { if (v > 10) alert('Limit reached'); });

5. Async Action in Option Store

async login(p) { this.user = await api.auth(p); }

6. Custom Reset in Setup Store

function $reset() { count.value = 0; name.value = ''; }

7. TypeScript Type Casting (Option)

state: () => ({ list: [] as string[] })

8. Injecting Provide/Inject (Setup)

const globalConfig = inject('config');

9. Multiple Store Interaction (Setup)

const otherStore = useOtherStore();
function doBoth() { otherStore.init(); this.localInit(); }

10. Returning Reactive Objects (Setup)

const state = reactive({ a: 1, b: 2 });
return { ...toRefs(state) };

Visual

Mapping Option vs. Setup

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  OPTION STORE STRUCTURE                                  โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚ state: () => ({ count: 0 }) <โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ DATA      โ”‚  โ”‚
โ”‚  โ”‚ getters: { double: (s) => ... } <โ”€โ”€โ”€โ”€โ”€โ”€โ”€ COMPUTED  โ”‚  โ”‚
โ”‚  โ”‚ actions: { inc() { this.count++ }} <โ”€โ”€โ”€โ”€ METHODS   โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                           โ”‚ (Functionally Equivalent)
                           โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SETUP STORE STRUCTURE                                   โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚ const count = ref(0); <โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ DATA      โ”‚  โ”‚
โ”‚  โ”‚ const double = computed(() => ...); <โ”€โ”€โ”€ COMPUTED  โ”‚  โ”‚
โ”‚  โ”‚ function inc() { count.value++; } <โ”€โ”€โ”€โ”€โ”€ METHODS   โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Internal Metadata Handling

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  defineStore()   โ”‚โ”€โ”€โ”€โ”€โ”€โ–บโ”‚  Pinia Internal Registry    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ”‚  ID: 'user'                 โ”‚
                          โ”‚  Type: [Option|Setup]       โ”‚
                          โ”‚  State: [Proxy Object]      โ”‚
                          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                        โ”‚
                          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                          โ”‚     VUE DEVTOOLS UI         โ”‚
                          โ”‚ [State] [Getters] [Actions] โ”‚
                          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Dependency Injection in Setup Store

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SETUP STORE FUNCTION                โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚  useRoute() hook               โ”‚  โ”‚
โ”‚  โ”‚        โ”‚                       โ”‚  โ”‚
โ”‚  โ”‚  const path = computed(...)    โ”‚  โ”‚
โ”‚  โ”‚        โ”‚                       โ”‚  โ”‚
โ”‚  โ”‚  return { path }               โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Factory FunctiondefineStore(id, ...)
Pattern AOption Store (Object)
Pattern BSetup Store (Function)
State Access (Option)this.propertyName
State Access (Setup)variableName.value
Native ResetOnly Option Stores
Composable SupportFull (in Setup Stores)
SSR SafetyHigh (both use function scope)

Key takeaways:

  • Option Stores provide structure. They are perfect for developers who want a clear separation of state, getters, and actions using an object literal .
  • Setup Stores provide flexibility. They allow you to use the full power of the Composition API, including watchers and external composables, inside the store .
  • Both are functionally identical to components. You can use as many stores as you want, and they will all share the same root Pinia instance .
  • Option Stores have a built-in $reset() method. This makes them ideal for forms or user sessions that need to be cleared easily .
  • Setup Stores require manual property return. You must explicitly return any property or method you want to be accessible outside the store .
  • TypeScript works excellently with both. Pinia handles the type inference for this in Option stores and standard variables in Setup stores .

Remember: Choosing a store style is a team decision. If you prefer the strictness of an object, use Option Stores. If you prefer the “Vue 3 way” with refs and computed, use Setup Stores. Both will produce a reactive, type-safe, and devtools-friendly store that integrates perfectly with the rest of your application.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!