Make your life easier with Vuex — The When, Why and How

let’s talk about Vuex and what makes it so awesome, followed by code examples. With Vuex, you get easily accessible, reactive and reliable app data. Integrating Vuex from the get-go, when dealing with complex apps, can save you a lot of time and effort.

Shahar Avigezer
Tailor Tech
6 min readFeb 18, 2019

--

Photo by Susan Yin on Unsplash

Intro To Vuex

Vuex is a state management library provided for Vue apps. A good state management system becomes crucial when your app gets more complex with a lot of moving pieces.

Vuex gives us the ability to store and share reactive data across the app without trading off performance, testability or maintainability. It empowers Vue’s reactivity system and creates easily accessible data between independent components, without having to deal with complicated prop drilling.

Another thing that makes Vuex so awesome is the developer experience that comes with it. For example, Vuex integrates perfectly with Vue’s developer tools, making it easy to track changes in the app’s state. It provides time-travel debugging, mutation commits history and much more — all without doing much on your end.

Should You Use Vuex?

Sometimes your code is so simple that you don’t need state management logic at all — for instance, a single page app with a few routes and a small data set. If this is the case, I’d stick to communication through props or implementing an event-driven system. Though, as your app grows, it makes sense to implement a state management solution. Vuex is the optimal solution in my opinion, so I recommend planning ahead and using Vuex as soon as a reason to do so arises, to save a lot refactoring in the long run.

Vuex vs. Redux

A more commonly used state management tool you might have heard about is Redux, which is mostly for React apps. Both of these tools are inspired by the Flux architecture for managing a state, but the main difference is the immutability of the state.

When we change data in Redux, the state will be entirely replaced, since it’s immutable. However, in Vuex, the state can be mutated directly using designated functions called Mutations. Vue automatically knows which components are using the state and need to be re-rendered upon changes. That’s right! You get a reliable, centralized and monitored state with the least amount of effort.

Another big advantage of Vuex is the ability to organize its state logic with stores called Modules instead of breaking down state logic with reducers like Redux. While using dynamically added modules, it can actually allow us to load different modules while using different parts of the app, so that can definitely come in handy in large apps.

How To Use Vuex?

When learning something new, I always prefer to use a real-world analogy to simplify the general concept and understand it better.

So, have you been to the library lately?
The library will be our example for the store. To understand the usage of Vuex as a whole, let’s take a familiar action related to the library, let’s say, like renting a book.

Let’s Get Coding!

Follow up with the code example on Github

Start with installing Vuex in your local Vue app:

npm install vuex --save

Now we are ready to create our Vuex store.

Store = Library

This is the container that holds the state. As I mentioned before, we can have multiple independent stores in one app, which gives us great flexibility. In our case, we’ll create a books.js file under src/store

In this file, we initialize Vuex and we tell Vue to use it.

State = Books array

This is the object that holds all the data. This single large object contains all your app level state and serves as the Single Source of Truth.

It’s likely you’ll want to pull data from a database server and update the state when on the app launch. In our case, we’ll simply initialize the array with dummy data.

Getter = availableBooks()

This is a function in our store that acts as computed properties, whose result is cached based on its dependencies and will only re-evaluate when some of its dependencies have changed. We can use it for values in the state or keep frequently used filters in one place to DRY up the store.

Mutation = toggleAvailablity()

As the name suggests, this handler function mutates the availability of a given book. The only way to make use of a mutation function is by committing (= calling) it. The “commit” command is used to record the state changes including which component committed the mutation. This ensures us a commit log, which we can later use for time-travel debugging. Think about how useful it can be to have such a rich history of all the changes and know exactly how and when the state was modified!

The state is received as the first argument, and we can also pass additional arguments - let’s say thebook object we want to modify.

That’s great and all, BUT

When you decide to rent a book, you don’t just grab one from the shelf and run off, right? At least, I hope you don’t; we’d be talking about a whole different action then….

We head over to the librarian to do the action for us- probably to mark the book as rented, log our name and date into the system, update availability in a larger database, etc.

To keep things in order, Vuex has decided to separate state changes and asynchronicity since it can make your app very hard to reason with. Synchronous mutations ensure that the state is not dependent on the timing of unpredictable events like API calls.

Action = rentBook()

These functions are the way to handle asynchronous operations since mutations have to be synchronous. It receives a context as the first argument, which allows us to use the same set of methods/properties on the store instance.

Another common use of actions is to perform multiple mutations. It is considered best practice to perform only one change in each mutation to keep your code clean and readable.

In our case, we’ll commit a couple of mutations and eventually toggle the book’s availability after calling the rentBook API.

Adding Vuex Store To The App

To showcase Vuex strengths in reactivity across multiple components, we’ll build two separate components that use the state:

  1. Library.vue — To present the number of available books
  2. BookList.vue — A list of the available books with a “Rent” button for each

Introducing the map helper
One cool thing in Vuex is the map helper for all the store objects. It comes out-of-the-box and in my opinion, this is a game-changer in the developer experience. It gives us the ability to map the store getter to local computed property with mapGetters, and store actions to component methods with mapActions

♫ So fresh and so clean ♫

Library.vue component

Let’s trigger the rentBook action in the other component:

BookList.vue component

Now, when we fetch or modify the state in any of the components, we can trust that our state is reliable and monitored!

To sum things up, Vuex is powerful and straightforward. Even though this is an uncomplicated example, it can help you understand how state managing can be efficient. Vuex makes working with Vue so much easier and fun. Give it a try in your next Vue app; I promise you, when you go Vuex — you never go back.

5 Important Takeaways

  1. state = data, stored as a single large object.
  2. getters are used to access values/frequently used filters in the state.
  3. mutations modify the state. Remember that mutations are synchronous.
  4. actions are for asynchronous operations and multiple mutations
  5. Use the mapGetters / mapMutations / mapActions helper to simplify your code

Hope this article was useful, feel free to CLAP and SHARE!

Follow on Medium or Twitter to learn more about how to improve your software development skills.

Read more:

Learn more about Tailor Brands and test out our state-of-the-art branding services. You can follow us on Twitter, Facebook and Github to see more exciting things that Tailor Tech is doing.

Come join our team — we’re hiring!

--

--

Shahar Avigezer
Tailor Tech

UX/UI designer turned Full Stack Developer, currently @ Riskified. Solving challenges both in tech and parenting.