tezvyn:

Pinia: Vue State Management That Feels Like Components

AI-drafted, machine-checkedSource: pinia.vuejs.orgadvanced
Pinia: Vue State Management That Feels Like Components

Pinia makes global Vue state feel like a component's local data. Create small, independent, type-safe stores for sharing data like user sessions or settings, avoiding complex prop drilling.

WHY IT EXISTS: Previous state management solutions for Vue could be verbose and encourage a single, monolithic state object that became difficult to manage in large applications. Pinia was created to offer a simpler, more modular, and more type-safe alternative that aligns with Vue 3's modern APIs, aiming to make state management feel like a natural extension of a component.

THE MENTAL MODEL: Think of Pinia not as one big database for your app, but as a collection of small, specialized JavaScript modules called "stores." Each store manages a specific piece of state, like a userStore or cartStore. You import and use only the store you need in any component, much like you'd import a helper function. It's state management à la carte, not a fixed-menu buffet.

HOW IT WORKS: You define a store with the defineStore function. Inside, you declare state, getters (computed state), and actions (methods) in a structure that intentionally mirrors a Vue component's data, computed, and methods. This makes it feel intuitive. Because each store is a self-contained module, bundlers can automatically code-split them, improving initial load performance. Pinia is also designed with TypeScript first, providing excellent autocompletion and type safety out of the box.

WHEN TO USE IT: Pinia is the standard choice for state management in Vue 3. Use it whenever you need to share state across different parts of your component tree without complex prop drilling, such as for user authentication status, theme settings, or a shopping cart. Its tiny size (~1.5kb) makes it a low-cost addition even for smaller projects.

WHEN NOT TO USE IT: For extremely simple apps where state is only passed down one or two component levels, prop drilling is often sufficient. If you're on a legacy Vue 2 project with a deeply integrated Vuex store, migrating may not be worth the refactoring cost unless you're already planning a move to Vue 3.

ONE CANONICAL EXAMPLE: A shopping cart is a perfect use case. A cartStore would hold an array of items in its state. It would have getters like cartTotal to calculate the price and actions like addItem or clearCart. A product listing page could call addItem, while a navigation bar component could display the cartTotal getter, both by importing and using the same cartStore without any direct component relationship.

Read the original → pinia.vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.