State Management
As applications grow in complexity, managing state across multiple components becomes challenging. Vue offers several approaches to state management, from simple reactive objects to full-featured state management libraries.When Do You Need State Management?
You might need centralized state management when:- Multiple components share the same state
- Components in different parts of the tree need to access the same data
- State needs to persist across route changes
- Complex state logic needs to be reused
- You need time-travel debugging or state persistence
Simple State Management
For smaller applications, a reactive object can serve as a simple store:Pinia - The Official State Management Library
Pinia is the officially recommended state management library for Vue. It provides a type-safe, intuitive API with excellent DevTools integration.Installation
Setup
Defining a Store
Options API Style
Setup Style
Using a Store
Destructuring with Reactivity
UsestoreToRefs() to destructure state while maintaining reactivity:
Core Concepts
State
The store’s data:Getters
Computed values derived from state:Actions
Methods that can modify state and perform async operations:Advanced Features
Subscribing to State Changes
Subscribing to Actions
Plugins
Extend Pinia with plugins:Hot Module Replacement
Preserve state during development:Composing Stores
Stores can use other stores:TypeScript Support
Pinia provides excellent TypeScript support out of the box:Testing
Unit Testing Stores
Testing Components with Stores
Migration from Vuex
If you’re migrating from Vuex:- No mutations - use actions directly
- No nested modules - create separate stores
- Simpler API with less boilerplate
- Better TypeScript support
- Smaller bundle size
Comparison
Vuex:Best Practices
- One store per domain - Separate stores by feature/domain
- Keep stores focused - Don’t create one massive store
- Use actions for async logic - Keep getters synchronous
- Compose stores - Reuse logic by accessing other stores
- Use TypeScript - Leverage type safety
- Avoid direct state mutation outside actions in Options API style
- Use plugins for cross-cutting concerns like persistence
- Test stores in isolation - Unit test store logic separately