Do You Really Need Vuex?
Let’s see in which cases we need to use a state management pattern like Vuex
Nowadays we overuse frameworks and libraries, just because they are popular but not because we need them.
I realized this by looking at the mistakes I made when I started using Vue.js.
At that time I did a lot of research and I noticed that everyone was using Vuex in Vue.js projects, so I started developing my first projects using Vuex too, and I was happy, it worked, it seemed useful and everyone used it, in short, it was cool.
I started using it for everything, even making simple API calls whose data was only used in a single component.
So I would like to help you to understand when it’s the right time to use Vuex.
What is Vuex
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application.
What makes Vuex very powerful is that the components get their data from the Vuex store and can reactively update whenever the store’s data changes.
You can read more here.
When should you use Vuex?
It’s time to use Vuex when you need to centralize data.
Let’s see two practical examples
Candy example 🍬
There is a house with 5 rooms, one of them is called STORE and inside there are 10 candies. From any other room, we can enter to the STORE and add, remove or just count the candies.
In our application, we have a list of items that we want to display differently in different components/pages. In this case, probably the best thing to do is to save the list of items on the Vuex store to make the list accessible from any component of our application.
As you can see, having a room (STORE) accessible from any other room/component can offer many advantages:
- save a lot of repeated code
- have a single source of truth
- accessible data(in writing and reading) across the application
- maintainable and scalable code
When should you not use Vuex?
When you don’t use the same data across your application and you don’t need to make them accessible from multiple places.
Before adding a new tool to your application, ask yourself if it’s really necessary and if it’s making your life easier.
Don’t increase the bundle size of your application for no reason.