Pinia 07 ๐ Store Architecture & Scaling โ Splitting stores by domain, composing with Vue composables, and avoiding circular dependencies
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
| Strategy | Description | Best For |
|---|---|---|
| Domain Splitting | Group by business entity (User, Cart) | Core application logic |
| Feature Splitting | Group by specific page or tool (Editor, Search) | Highly isolated features |
| UI Splitting | Group by global UI state (Modals, Toasts) | Cross-cutting visual concerns |
| Hybrid | Domain for data, Feature for local page state | Large, complex applications |
Dependency Management Patterns
| Pattern | Technique | Use Case |
|---|---|---|
| Direct Import | import { useA } from './a' | Standard store-to-store logic |
| Delayed Injection | Call useA() inside an action | Avoiding Circular Dependencies |
| Composable | Wrap logic in useX() function | Reusing logic across multiple stores |
| Plugin | Use 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Circular Dependency | Store A imports B, and B imports A at top level | Call useOtherStore() inside an action or getter |
| State Bloat | Adding UI state to domain stores unnecessarily | Create local page stores or a generic UI store |
| Inconsistent Data | Multiple stores holding copies of the same data | One store is the “Source of Truth”; others use getters |
| SSR Issues | Using composables that depend on window | Wrap in if (process.client) or use SSR-safe helpers |
| Naming Collisions | Short, generic store IDs like store or data | Use 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
| Item | Value |
|---|---|
| Scaling Philosophy | Flat, modular, domain-driven |
| Organizing Principle | Business entities (User, Product, Order) |
| Reuse Pattern | Vue Composables + Store Composition |
| Loop Prevention | Delayed Injection (call inside actions) |
| Performance | Route-based code splitting / Tree Shaking |
| Testing | Isolated unit tests per domain |
| Tooling | Vite + Pinia DevTools |
| Maintainability | High (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/coreinside 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
stateproperty 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.
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!