| | |

Pinia 07 ๐Ÿ Store Architecture & Scaling โ€” Splitting stores by domain, composing with Vue composables, and avoiding circular dependencies

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

As applications move beyond simple prototypes, the strategy for managing state becomes as important as the state itself. In the early days of state management, developers were often forced into a “Monolithic” pattern where a single massive object held the entire application’s data. Pinia fundamentally rejects this approach in favor of a modular, flat architecture. This modularity allows for better code splitting, easier testing, and a clear mental model of how data flows through different parts of the system.

Scaling a Pinia application effectively requires a deep understanding of domain-driven design. Instead of organizing stores by technical categories (like “loadingStatesStore”), successful architectures organize stores by business entities, such as UserStore, CartStore, and ProductStore. This ensures that logic related to a specific part of the business remains encapsulated, making it easier to maintain and refactor without triggering unexpected side effects across the rest of the application.

This chapter details the advanced architectural patterns required for large-scale Vue applications. We will examine how to split stores by domain, how to leverage Vue’s Composition API and external composables within store definitions, and how to identify and resolve the dreaded circular dependency. By the end of this tutorial, you will have a blueprint for building a state management layer that can support hundreds of routes and complex data relationships without collapsing under its own weight.

Key point: Effective Pinia architecture relies on a “Flat Store” philosophy where domain-specific stores communicate via composition, avoiding monolithic structures and managing circular dependencies through delayed store instantiation.


Why exists

The “God Object” Problem. In monolithic state management, a single store grows so large that it becomes impossible to reason about. Developers end up with thousands of lines of code in one file, where a change in one corner of the state breaks a completely unrelated feature. Splitting by domain ensures that no single file becomes a “God Object” that controls everything.

The Bundle Size Problem. If your entire application’s state is in one file, a user visiting a simple “About” page might still be forced to download the code for the “Admin Analytics Dashboard.” Modular stores allow build tools like Vite to perform “Tree Shaking,” ensuring that users only download the state logic required for the features they are actually using.

The Spaghetti Dependency Problem. Without a clear strategy for store-to-store communication, applications quickly become a web of interconnected logic where Store A calls Store B, which calls Store C, which eventually calls Store A again. This “Spaghetti” architecture makes the app fragile and difficult to debug.

The Logic Duplication Problem. Common logic, like handling API pagination or formatting currency, shouldn’t be rewritten in every store. Architecture patterns like “Store Composition” allow developers to write reusable logic once and share it across multiple stores, either through custom composables or by having one store consume another.

The Testing Bottleneck. Testing a monolithic store is a nightmare because you have to mock the entire world to test a single function. Modular stores allow for isolated unit tests where you only need to mock the specific dependencies of the domain you are testing, leading to faster and more reliable CI/CD pipelines.

The Namespace Collision Problem. In large teams, two developers might accidentally create a state property called loading. With a modular architecture, one developer works on CartStore.loading while another works on AuthStore.loading. The domain splitting provides a natural namespace that prevents these collisions.


a. Splitting by Domain

The first rule of Pinia architecture is to split stores based on their domain (the “what” of the application) rather than their technical function. A domain-driven store contains the state, getters, and actions related to a single business entity or a logical group of features. For example, in an e-commerce app, you would have useUserStore, useProductStore, and useOrderStore.

// src/stores/user.js
export const useUserStore = defineStore('user', {
  state: () => ({ profile: null, preferences: {} }),
  actions: {
    async fetchProfile() { /* ... */ }
  }
});

// src/stores/cart.js
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  actions: {
    addItem(product) { /* ... */ }
  }
});

By keeping these stores separate, you create boundaries. The CartStore doesn’t need to know how the UserStore fetches a profile; it only needs to know if a user is logged in before allowing a checkout. This separation of concerns is what allows multiple developers to work on different parts of the application simultaneously without stepping on each other’s toes.

A common mistake is creating “Global UI” stores. While it is tempting to put all modals, sidebars, and notification states into a single useUIStore, it is often better to attach that state to the domain it belongs to. If a sidebar is specifically for filtering products, that state might actually belong in the useProductStore.


b. Store Composition and Composables

One of Pinia’s greatest strengths is its ability to use other stores and Vue composables directly inside a store definition. Because Pinia stores are built using the same reactivity engine as Vue components, you can call useOtherStore() inside an action or a getter. This allows for complex logic where one domain depends on another.

import { useAuthStore } from './auth';

export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  actions: {
    async checkout() {
      const auth = useAuthStore(); // Accessing another store
      if (!auth.isLoggedIn) {
        throw new Error('User must be logged in');
      }
      // Proceed with checkout...
    }
  }
});

Furthermore, you can use external composables (like those from @vueuse/core) to enhance your stores. For example, you can use useLocalStorage to make a store property persistent with zero manual effort, or useOnline to change store behavior based on the user’s internet connection.

import { useLocalStorage } from '@vueuse/core';

export const useSettingsStore = defineStore('settings', () => {
  // Using a composable to manage state
  const theme = useLocalStorage('theme', 'light');

  function toggleTheme() {
    theme.value = theme.value === 'light' ? 'dark' : 'light';
  }

  return { theme, toggleTheme };
});

c. Avoiding Circular Dependencies

Circular dependencies occur when Store A imports Store B, and Store B imports Store A. If these imports happen at the top of the file, the JavaScript engine might encounter an “undefined” reference because one of the stores hasn’t finished initializing when the other tries to use it. This often results in cryptic errors like Cannot access 'useAStore' before initialization.

The fix for circular dependencies in Pinia is “Delayed Instantiation.” Instead of calling useOtherStore() at the top of your file or outside the defineStore function, you call it inside the action, getter, or computed property where it is actually needed.

// โŒ BAD: Potential circular dependency if Auth also imports Cart
const auth = useAuthStore(); 
export const useCartStore = defineStore('cart', { ... });

// โœ… GOOD: Delayed instantiation
export const useCartStore = defineStore('cart', {
  actions: {
    doSomething() {
      const auth = useAuthStore(); // Called only when action runs
      console.log(auth.user);
    }
  }
});

In Setup Stores (function syntax), you can define the other store inside the setup function, but you should still be careful. If Store A and Store B both call each other immediately during their setup phase, you will still hit a circular loop. The safest place to call a dependency store is always inside an asynchronous action or a dynamic getter.


Complete Example Session

// ============================================
// PART 1: THE AUTH STORE (Identity Domain)
// ============================================
export const useAuthStore = defineStore('auth', () => {
  const user = ref(null);
  const isLoggedIn = computed(() => !!user.value);
  return { user, isLoggedIn };
});

// ============================================
// PART 2: THE PREFERENCES STORE (Settings Domain)
// ============================================
import { useLocalStorage } from '@vueuse/core';
export const usePrefsStore = defineStore('prefs', () => {
  const language = useLocalStorage('lang', 'en'); // Composable
  return { language };
});

// ============================================
// PART 3: THE NOTIFICATION STORE (UI Domain)
// ============================================
export const useNotifyStore = defineStore('notify', {
  state: () => ({ messages: [] }),
  actions: {
    push(msg) { this.messages.push(msg); }
  }
});

// ============================================
// PART 4: THE CART STORE (E-commerce Domain)
// ============================================
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  actions: {
    async checkout() {
      // PART 5: COMPOSING STORES (Accessing Auth)
      const auth = useAuthStore(); 
      if (!auth.isLoggedIn) {
        // PART 6: CROSS-STORE ACTIONS (Accessing Notify)
        const notify = useNotifyStore();
        notify.push('Please login first');
        return;
      }
      // Logic for checkout...
    }
  }
});

// ============================================
// PART 7: THE REUSABLE PAGINATION COMPOSABLE
// ============================================
export function usePagination(apiEndpoint) {
  const page = ref(1);
  const data = ref([]);
  const fetch = async () => { /* api logic */ };
  return { page, data, fetch };
}

// ============================================
// PART 8: USING COMPOSABLES IN STORES
// ============================================
export const useProductStore = defineStore('products', () => {
  const { page, data, fetch } = usePagination('/api/products');
  return { page, data, fetch };
});

// ============================================
// PART 9: HANDLING CIRCULAR REFS IN GETTERS
// ============================================
export const useReportStore = defineStore('reports', {
  getters: {
    summary(state) {
      // Instantiated inside getter to avoid top-level loops
      const products = useProductStore();
      return `Reporting on ${products.data.length} products`;
    }
  }
});

// ============================================
// PART 10: SHARED TYPES AND INTERFACES
// ============================================
// (Conceptual) Shared domain models help keep stores in sync.

The sequence above shows a modular architecture where identity, settings, UI, and business logic are separated, composed, and safely interconnected.


Quick Reference

Store Organization Strategies

StrategyDescriptionBest For
Domain SplittingGroup by business entity (User, Cart)Core application logic
Feature SplittingGroup by specific page or tool (Editor, Search)Highly isolated features
UI SplittingGroup by global UI state (Modals, Toasts)Cross-cutting visual concerns
HybridDomain for data, Feature for local page stateLarge, complex applications

Dependency Management Patterns

PatternTechniqueUse Case
Direct Importimport { useA } from './a'Standard store-to-store logic
Delayed InjectionCall useA() inside an actionAvoiding Circular Dependencies
ComposableWrap logic in useX() functionReusing logic across multiple stores
PluginUse pinia.use()Global cross-store augmentation

Best Practices

โœ… Do This:

// Split stores by domain entity
export const useOrderStore = defineStore('orders', { ... }); // โœ…
// Call dependent stores inside actions/getters
const auth = useAuthStore(); // (inside an action)            // โœ…
// Use descriptive IDs for your stores
defineStore('ecommerce-shopping-cart', { ... });             // โœ…
// Use VueUse composables for storage or sensors
const theme = useLocalStorage('theme', 'dark');              // โœ…
// Group related stores in a /stores directory
src/stores/auth.js, src/stores/cart.js                       // โœ…

โŒ Don’t Do This:

// Create one massive "MainStore"
export const useMainStore = defineStore('main', { ... });    // โŒ
// Call useOtherStore() at the top level of a file
const auth = useAuthStore(); export const useStore = ...     // โŒ
// Duplicate API logic in every store
actions: { async fetch() { /* copy-pasted code */ } }       // โŒ
// Hardcode cross-store state dependencies
state: () => ({ userName: useAuthStore().name })             // โŒ
// (State should be a plain object, not dependent on others)

Common Pitfalls

PitfallWhy It HappensFix
Circular DependencyStore A imports B, and B imports A at top levelCall useOtherStore() inside an action or getter
State BloatAdding UI state to domain stores unnecessarilyCreate local page stores or a generic UI store
Inconsistent DataMultiple stores holding copies of the same dataOne store is the “Source of Truth”; others use getters
SSR IssuesUsing composables that depend on windowWrap in if (process.client) or use SSR-safe helpers
Naming CollisionsShort, generic store IDs like store or dataUse prefixed IDs: app-user, settings-profile

Real-World Examples

1. Domain split: User management

export const useUserStore = defineStore('user', { ... });

2. Domain split: Product catalog

export const useCatalogStore = defineStore('catalog', { ... });

3. Delayed call to avoid loop

const action = () => { const other = useOtherStore(); };

4. Persistent settings via composable

const lang = useLocalStorage('language', 'en');

5. Cross-store validation

if (useAuthStore().isAdmin) { /* allow delete */ }

6. Reusable pagination hook

const { list, next } = usePagination('/items');

7. Global Toast registry

useToastStore().add('Saved successfully');

8. Composing Auth into Checkout

const checkout = () => { if (useAuth().valid) ... };

9. Responsive state in store

const isMobile = useBreakpoints().mobile;

10. Multi-store reset action

actions: { clear() { useCart().$reset(); useUser().$reset(); } }

Visual

Flat Architecture Pattern

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  AuthStore   โ”‚      โ”‚  CartStore   โ”‚      โ”‚ ProductStore โ”‚
โ”‚ (Identity)   โ”‚      โ”‚ (Checkout)   โ”‚      โ”‚ (Catalog)    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚                     โ”‚                     โ”‚
       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”          โ”‚          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                  โ–ผ          โ–ผ          โ–ผ
            โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
            โ”‚       APP COMPONENTS / VIEWS     โ”‚
            โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Resolving Circular Loops

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”             โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     STORE A     โ”‚             โ”‚     STORE B     โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค             โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  actionRun() {  โ”‚             โ”‚  actionGo() {   โ”‚
โ”‚    const b =    โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚    const a =    โ”‚
โ”‚    useStoreB()  โ”‚             โ”‚    useStoreA()  โ”‚
โ”‚  }              โ”‚โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚  }              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜             โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
 (Instantiated only during execution, avoiding build-time loops)

Composable Integration

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Pinia Store                                              โ”‚
โ”‚                                                          โ”‚
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚ โ”‚ Core State       โ”‚      โ”‚ Shared Composables        โ”‚  โ”‚
โ”‚ โ”‚ { id, name }     โ”‚ +    โ”‚ useLocalStorage()         โ”‚  โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ”‚ usePagination()           โ”‚  โ”‚
โ”‚                           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Scaling PhilosophyFlat, modular, domain-driven
Organizing PrincipleBusiness entities (User, Product, Order)
Reuse PatternVue Composables + Store Composition
Loop PreventionDelayed Injection (call inside actions)
PerformanceRoute-based code splitting / Tree Shaking
TestingIsolated unit tests per domain
ToolingVite + Pinia DevTools
MaintainabilityHigh (clean separation of concerns)

Key takeaways:

  • Avoid the Monolith. Modular stores are the key to a scalable Vue application. Group your data by domain (e.g., Auth, Cart, Products) to ensure your code remains manageable and tree-shakable .
  • Stores are composable. You can call one store inside another, but do so carefully. This allows you to build complex features that span multiple domains without duplicating data .
  • Delayed instantiation fixes circular loops. If Store A needs B and B needs A, call useStoreX() inside an action or getter rather than at the top of the file .
  • Leverage the ecosystem. Use composables like @vueuse/core inside your store definitions to handle cross-cutting concerns like LocalStorage, device sensors, or network status .
  • Encapsulate logic. Don’t just store data; store the actions that modify that data. If multiple components perform the same API call, move that logic into a store action .
  • Keep state serializable. While getters and actions can be complex, keep your state property as simple as possible (objects, arrays, primitives) to ensure compatibility with SSR and devtools .

Remember: Scaling Pinia is not about finding a bigger container for your data; it’s about breaking that data into logical, independent modules that communicate through clear interfaces.

Pinia Architecture, Store Composition, Circular Dependencies, Vue Composables in Stores, Domain Driven Design Pinia, Scaling Pinia Stores, Pinia Setup Stores vs Option Stores, Modular State Management Vue, Code Splitting Pinia, Vite Tree Shaking Pinia, Vue Architecture Patterns, Circular Ref Pinia Fix, useAuthStore Pinia Example, Pinia Project Structure, Vue 3 State Scaling, Composables in Pinia actions, Global State Organization.

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!