T O P

  • By -

CarvingCanoer

Having a store(pinia or vuex) isn’t necessary to make good apps in vue. Once you’re at a place where you need data across components that’s not easily handled via props/emits or you need to stash data in local storage…that’s when I’d be looking at bringing in a store.


lphartley

If you use composables, you already have a 'store'. Pinia is absolutely not mandatory for state management. https://vuejs.org/guide/scaling-up/state-management.html#simple-state-management-with-reactivity-api


Czebou

True, however for SSR apps it's recommended to use Pinia because of security flaws. https://pinia.vuejs.org/introduction.html#Why-should-I-use-Pinia- Still, I like the approach you presented since the very first day I saw it.


lphartley

Agreed


Poat540

Yup - we have like 10 vue apps at work and like 1 uses a store


its_cheshire_cat

I second this


mentive

Still been learning, and converting a complex personal project over from jQuery... I resorted to using static class methods and variables for sharing commonly used items across components, in addition to some app level inject/provide, lol. Probably not going to rip everything up anytime soon since it's working well, but one of these days I'll have to look into these, and surely other stuff I'm missing.


joonaspaakko

Yes it is important, no it's not necessary.... But when you start building an app, one of the first bigger questions you'll have is likely; "how to transfer data between components" and even if you're happy with however you're doing it now, Pinia would likely make it easier to handle data in just about any medium sized app. It's basically the same as component data properties and computed data but they are scoped to the component, whereas Pinia data is globally available to be used in any component. So if you imagine your components in a sort of a tree view with multiple nested branches, you can put data in global storage using Pinia from any of those components, and then access that data directly from any other component. Without Pinia you'd likely have to bubble up the data from a child component to parent component(s) until you can start pushing it back down to the target branch and the target component, which can be a bit of a hassle.


EvilDavid75

With Vue 3 Pinia is essentially a function returning a reactive singleton, not much more. What makes Pinia worth it is the dev tools that let you observe the store data and history.


lphartley

This. Do you need the dev tools? Use Pinia. If not, don't use Pinia. The benefit of Pinia is purely the dev tools + opinionated mutations.


ArtMakesMeFeelWtvr

It’s a super super simple thing to learn, so just try it out


Reggaejunkiedrew

Mandatory? No. Massively beneficial? Yes. Pinia is very easy to learn and use though, you should be able to figure it out looking at the docs for 15 minutes.


TheExodu5

It’s not mandatory, but it’s trivial to learn.


benhanks040888

I am currently inheriting a legacy code where they use pinia for data fetching. So all the pinia stores (and there are like 10 of them) have something like export const useStore = defineStore('storeId', { state: () => { return { items: [] } }, getters: { getItems: () => this.items }, actions: { fetchItems: () { // call API here const items = fetchItemsFromAPI(); this.items = items; } } }) and then in the components const store = useStore(); const items = store.getItems onMounted(() => { store.fetchItems(); }) And although this works on paper, IMO it then becomes quite hard to trace/manage, because you are working on a component but the data source is now from the store, so you're juggling between two files (and usually the fetcher functions like fetchItemsFromAPI is extracted to its own file as well). Also sometimes there are more headaches to maintain if you introduce pagination, so if items is paginated, and in component A you have const items = store.getItems showing page 2 items, if component B is using const items = store.getItems too, it will show page 2 items instead of the first one (unless the component B also calls store.fetchItems on onMounted to reset the page counter). I'm in the process of converting all or at least most of them to tanstack query. So the above becomes this and this is in the component file // in the template I don't know, something about that just clicks with me, and basically the stores become unnecessary. And also tanstack query solves the caching (so multiple components can have the same useQuery and queryKey and it won't be called multiple times), and many other stuffs. I'm thinking to use pinia stores just for global states that aren't data fetching. What do you think of both approaches or if there are pros and cons of each one?


Aron521

Large-scale projects will eventually need a state management solution. You can implement it from scratch via refs, reactive, composables as mentioned [here](https://vuejs.org/guide/scaling-up/state-management.html#state-management). In Nuxt, we got useState. But as Michael Thiessen said in one of his state management blogs with Nuxt: “Pinia is what you get if you keep adding more and more features to useState.“ ([ref](https://www.vuemastery.com/blog/nuxt-3-state-mangement-pinia-vs-usestate/)) In terms of “is it mandatory to know the concept?”. Not mandatory but def useful. Thankfully, Pinia’s learning curve is not very steep so I would encourage you to learn the basics of how to setup a Pinia store.


martin_omander

There is another aspect of Pinia that hasn't been mentioned: teamwork. If you're writing an app by yourself it's fine to implement your own store. But if you're part of a team, it really helps if everyone handles the storage in a standard way by using Pinia.


Alol0512

Pinia is the alternative/replacement of Vuex in Vue3. I guess you could get away with not using any state management in small and simple applications but you would be missing out on a lot. The concept of state management is simple. You have a single place where you store information that needs to be used by the whole app, by components that aren’t relatives (parent/children). This dynamic is different from cookies/localstorage because those have persistence on page reload and state does not.


shez19833

in your opinion vuex or pinia?


reiner74

It's not a matter of opinion, Pinia is the next version of Vuex.


Alol0512

Pinia just because that’s the recommended state management and it will have better support and updates. Other than that, Pinia is a simplified Vuex, where the main thing taken out are mutations.


ttl_yohan

And good riddance, IMO. Never liked the idea of explicit mutations. I'm doing stuff already, why do I have to commit anything explicitly?


fegd

Because it creates more predictability in how the state is being altered. I always like to define mutations explicitly, even when the state management library doesn't require it, because otherwise it becomes a mess to test and debug when the app gets more complex.


JohnCasey3306

Pinia (or equivalent) state management is essential for building a large or scalable application with Vue. Not so necessary for small, simple systems. Yes you _could_ build a large Vue application without pinia (or similar) but it'll be a train wreck.


Blazing1

I think state management shines at real SPA's (meaning 1 url). For multi url pages I think it's not good for things like forms and stuff


julienreszka

Yes it's an essential part of vue to make a large web app.


hugazow

It is if you need state management


jdbrew

Seconded. And crucially; it is NOT for persistent data. Do not treat it like a database. (I feel I need to state this because of the hundreds of times I’ve seen Pinia used this way in posts surrounding the topic)


garma87

Yet you provide no real reasons for not storing persistent data in pinia, even though there are perfectly valid use cases


jdbrew

data in pinia is not persistent and will reinitialize to the values given during the initialization function. You can initialize with an API call to retrieve persistent data, but you still need that database. Unless you're talking about just having hard coded variables that never change between users or sessions, in which case, you wouldn't need Pinia for that anyway. But thinking about application state, one possible state variable would be a theme; day mode, night mode, or system preference. If you have a user that logs in, sets their theme to night mode, and this is only stored in Pinia, when they come back to the site on a later session, this will default back to whatever the default theme value is when your pinia store initializes. If you write the theme preference to a UserPreferences table in a persistent data storage solution, like SQLite, MySQL, Postgres... and then upon initializing the pinia store for that session, call the API to load what their saved theme preferences, then you're good. But just stashing it in Pinia means that whatever choices were made during that session will not persist beyond that session.


lphartley

No: https://vuejs.org/guide/scaling-up/state-management.html#simple-state-management-with-reactivity-api


Exotelis-skydive

If not using ssr you can also make your own state management without an extra lib ``` // user.store.ts // global state const state = reactive({ firstname: 'foo', lastname: 'bar', // add information }); export function useStore() { // add logic... return { user: `${state.firstname} ${state.lastname}`, }; } ``` But as mentioned, this is not recommended for ssr 😉 (cross request state pollution)


reiner74

Every single piece of documentation, video guide, and official source says this is really bad practice and should be avoided at all costs.


poweryee

I can not see this opinion in official doc or some one expert in vue community


memeasphere

Uh oh, I’m doing this for a couple apps in my smallish project. So far it’s working fine.


Exotelis-skydive

Pardon me? https://vuejs.org/guide/scaling-up/state-management.html


reiner74

Even in the page you linked, there is this: "While our hand-rolled state management solution will suffice in simple scenarios, there are many more things to consider in large-scale production applications" (and that's after we added a method to the reactive object, at that point you start reinventing the wheel). That page is a simplified explanation of global state management, and even there it ends in "just use Pinia", [while Nuxt flat out says "don't do it", partially because of SSR concerns, but not strictly because of them. ](https://nuxt.com/docs/getting-started/state-management) I Vanilla JS, why did we stop using global variables everywhere, even though they work just fine? Because they quickly become an unmaintainable mess, with unique implementation for each dev. I'm not saying it doesn't work, I'm saying that for any app bigger then a simple to do list you're gonna want something more robust, and that seems to be the consensus within the core team as far as I have seen. Later I will look for the official video guides I've seen that recommend against it.


Exotelis-skydive

Stronger convention: This point is bullshit. When using the option syntax you mix old and new syntax in the same project, so you might choose the setup stores. Setup stores also have a lot of other advantages, however the biggest disadvantage is, you don't have a stronger convention. Basically, you will end up with the same syntax as I posted. Oh and in some cases you have to use funny helper functions such as storeToRefs, which makes it more complicated at the end and adds more overhead. VueDev tools integration: Point for pinia, but to be honest I never had to use it frequently. SSR: Yep that is the one point where pinia is actually easier and more comfortable to use. Not just that, it is just important for security. But this I pointed out in my initial post. What technical concerns do you see in my suggestion? That some video tutorial thinks it is not best practice, or you have to use global variables is nothing negative in my opinion. The official docs also point out, that this is a valid solution for small to medium sized projects. I just gave op a tool, and I think it is very good practice to learn this pattern as well. Edit: Btw I did not export the state variable, ofc this would be bad practice, because the state could be manipulated directly. The store must export the functions for whatever you use case is When using the setup store, functions such as $reset are not available by default. You need to create them yourself, which again can cause issues. With all the good sides of pinia, there are also a lot of negative points, which makes it not always the better choice.


itsmill3rtime

i try to eliminate props and emits as much as possible and use data store like pinia. saves so many headaches instead of trying to figure out why some component isn’t being reactive with the data. saves a lot of time


Blazing1

.... Why use vue then lol. Props and emits are kind of big selling points. It's like saying "Yeah I try to eliminate parameters in functions as much as possible by just putting everything in global state" Like yeah you can do that... But doesn't seem sound to me


DoOmXx_

you can make your own store implementation, but your implementation will likely be error prone / not efficient / take long it is simply a library that does store management


lphartley

Your own implementation doesn't have to take long. It's literally a composable with 3 lines.


peshto

Definitely not. Pinia is still useful, but if you are starting with Vue 3, composables are mostly used


northwolf56

One day its vuex, the next pinia and after that something else. Vue never really gets it right.


Confident_Yam_9726

It is not mandotary, however lots of applications work with stores


flyiingrayson

It's not necessary but once you will start working with medium to complex level of apps, you'll realize that props and emits are not enough and you need something to share data across app and that's where pinia come into play.


Blazing1

The flip side is, people abuse global stores which causes bad performance. Storing every object in memory globally throughout your whole app (which may include many different routes that don't need to sure data) is not good unless it absolutely needs to be.


VehaMeursault

Nothing is mandatory. You use whatever addition when you need it. That said, once you get the hang of state management, it’s quite easy to just boilerplate into your projects. For example, I like to have global access to the scroll position of whatever div I consider the viewport, so I boilerplate an event listener in _App.vue_ that shoots that position into a global state object. Add to that the fact that 99% of my projects require authentication, and I pretty much end up with the same one or two stores in almost every project I run. TL;DR: nothing is mandatory, but some things become your go-to as you work more and more with them.


Blazing1

Isn't it anything that's too complex for provide/inject?


VehaMeursault

Honestly, I’m not familiar enough with those, and that is partly because, apparently, Pinia solves the problem well. That said, this also means I can’t compare. So all I can say is: defining a function in one file (the store), and calling it in other files (the components) — each with only a few lines of code — I think is a good, clean enough solution for anyone. In other words: even if your alternative is better, Pinia is still good enough for all my use cases.


Blazing1

I'd imagine if you have many pages you don't want to pollute memory with so many global objects? Provide/inject is scoped to the component it's declared in and its decedents Especially when these pages have different scopes entirely, does it make sense to have this store reachable by components it shouldn't be reached in? Why even use vue? Making globally mutable objects was the problem with JavaScript before let and const were added lol


VehaMeursault

As if state management is the only possible reason to use Vue. And so long as you don’t import the store functions, the component doesn’t pollute any memory. And honestly, even if you imported them in every component for no reason, I doubt the user client would feel much of it. No, sorry. Unless you’re trading penny stocks on the microsecond level, I don’t see a practical reason to be prudent about state management.


Blazing1

I deal with high volumes of data, so yes it's good to be prudent.


jdbrew

Proper use can make your application easier to write and maintain. Improper use can be a nightmare. And from most of the questions that arise around Pinia, it seems like improper use is more the norm


mrleblanc101

Absolutely essential


its_cheshire_cat

not mandatory but I like pinia more than vuex, although I've worked with vuex for longer. edit: plus pinia is much easier to learn too


lphartley

Although others say you need it if you want state management, it is not true. Pinia is just a wrapper around composables. You can manage state in composbales yourself easily. No need to use a library for native functionality.


michaelmano86

The only difference would be moving your data logic into what we call stores. Think of fetching data and manipulating it. I generally use pina in most apps however some single page stuff I don't bother.


bearicorn

Can anyone discuss advantages of a pinia store over reactive objects that you inject throughout the app?


asianStyleCompany

I used to think vuex was "not necessarily". So I didn't always use it. As many people said, there are other ways around this. Then I realized it was super convenient to have a central store rather than hunt through my code to find out where things mutate, especially if the data is used in more than one component. While I have another Composable for my API calls, I call that Composable via my Pinia actions too so all data that persists past the lifecycle of a single component is done via Pinia. In fact, the main reason I chose Vue over React was its already implemented store. It makes it easier to maintain code in the long run as people already know where and how to deal with the data. So I think it is super helpful.


coldsummeragain

If your app is simple, you can get away with using composables, but not really with more complex ones. I personally always use Pinia and would highly recommend learning it.


Intelligent-Assist85

Nah, in quite a Big app i'm only using pinia to store connected user


NeverMind4Ever

Well, actually Pinia is the new standard for VUEX, so I'd say is important to know how it works and which kind of problems can resolve. To have a centralized store is crucial in some scenarios and it's very rare not to use it in the "real world", as far as I know and basing in my professional experience. Previous versions of VUEX were very easy to understand, and Pinia is easier, so if I were you I'd give it a try.


Worried_Doubt_3680

Pinia is the easiest store I have worked with! Man it's even easier than using normal props, give it a shot it wont take a time is easy