The Vue 3 Reactivity and Composition API offers developers flexible techniques to work with reactive data. They enable a new and modern approach to handling State Management. Developers can now effortlessly implement local and global stores. Vuex has been one of the most used First-party plugins for Vue 2. Let's have a look at the advantages and tradeoffs of using Composables instead of Vuex.
Modern State Management with Vue 3
AI Generated Video Summary
Vanessa introduces Vue Free and discusses the benefits of using the Composition API. The order of execution and grouping logical units using the Composition API is explained. The Composition API is used for state management and refactoring components. The speaker shares their initial experience with state management using Vuex. Composables are explored as an alternative for state management in Vue 3.
1. Introduction to Vue Free and the Composition API
In this part, Vanessa introduces Vue Free, a powerful state management solution for Vue applications. She shares her journey of using Vue Free without Options API and Vuex, leveraging the Composition API instead. Vanessa explains the benefits of the Composition API and how it can be used in small applications. She also discusses the three APIs in Vue: options API, reactivity API, and composition API, highlighting the advantages of the composition API. Finally, she provides a recap of writing a component in Vue 2 or Vue 3 using the options API.
Hi, I'm Vanessa. You can find me online as Vanze. I'm responsible for the front end at Cevy. I'm co-host of two different podcasts, Expect Exception, where we talk about front-end testing and Working Draft, a German podcast about web development. And roughly a year ago, in September, 2020, I can remember as I sat there watching Avenu on the Vue JS conference, finally saying, hey, Vue Free is out there, and now I want you to go with me on the journey, how I installed Vue Free and used alternative concepts to use Vue Free completely without Options API and also without VueX. I do not suggest that you should use Vue Free without Options API or replace VueX. I want to tell you that the Composition API is so powerful that we actually can use Vue without both of those tools, and it made sense for me in a state where I had a really small application which I started with Vue Free from scratch and did not have to migrate from my Vue2 application.
In the code examples I will show in the next couple of minutes, I will use the set up function and I prefer to use ref over reactive. But everything I will show now you of course can use the script setup syntactic sugar instead and you can choose to use reactive instead of ref if you prefer to.
As my components of my very small Vue Free application roughly a year ago started to grow because I had some more complex problems which needed some more complex solutions, I and therefore also this talk were mainly inspired by those three articles. Group, extract share pattern, state management with composition API, and should you use composition API as a replacement for Vuex.
So let's have a recap of how to write a component in Vue 2 or in Vue 3 using the options. Here I have a template with a paragraph with greeting and full name. If I scroll down to my script block, I can see here that I have a data function, which is a turning an object with greeting and hello. I have properties for first name and last name. And I have a computed property for the full name, which is returning me a first name with a spice and the last name. So this is one component with just one purpose, which is doing its job quite well. Kind of a funny side note is that I initialized this greeting here as a reactive data attribute, although I actually don't ever change it and won't need this observers on it anyway. But I was never sure where to put this constants using the options API. The problem I now want to focus on is that logical units, if the component is growing and growing, are spread over the whole script block. So what do I mean with this? I've prepared this code sandbox here, and here we can see as well we have our greeting and full name to say hello to the user.
2. Order of Execution and Grouping Logical Units
But then we also displayed the user's items where we loop over and also provide a delete item function to delete something. If I scroll down to the script block, I now want you to focus on the order of how things are happening. I have the data function which is running an object with the greeting and items. The properties having stuff from the greeting. A computed property with a full name of the greeting. Then a method with the function delete item of the items. The categories bind to the way that the view skeleton, the view object here is structured.
Everything in data is in data. Every computed property is in computed property. Every function is in the methods block. Now we have a point where we have now greeting items, greeting, greeting items. They are shattered over the whole file. This is kind of, it grows and grows and grows, looking like this. Of course it can be a solution to split the component, but let's focus on it doesn't work anymore, we can't split any further, and we still have this lines of code not really bind together and what the composition API is providing us with is a possibility to group logical units together again, so that everything is related to the greeting, we can imagine being in this light blue box on the top and everything related to the items we can imagine to be bind together in this darkish blue, almost black box here. So the composition API enables developers to encapsulate logical units in one single file or in shared with others.
3. Composition API and State Management
In this part, the speaker discusses using the composition API to group logical units and refactor components. They demonstrate how to encapsulate functionality in separate functions and return necessary properties. The use of ECMAScript destructuring is explored, along with the importance of explicit imports for better IDE support. The speaker also mentions the Vue Use Git repository as a resource for prewritten composables. They then transition to discussing state management, highlighting the drawbacks of props drilling and using the global root object in Vue 2.
Just a const, and when they have a full name as computed property. But of course, also here the functionality can grow a bit. We are switching to our Hello World 2 component, and where I have also my items, which I also can delete. I loop over them in the template and I have my method to delete them. I import computed and ref now from you, and if I now scroll down to the setup block, what we can see is the same implementation for greeting with a greeting and full name, and then a logical unit of the items and a method to delete the items.
And as I started with U3, all of the time my muscle memory was like, oh yeah, I have to put everything data related in the beginning, and then all over the computed properties and then all of the methods and then all of the lifecycle hooks until I remembered, no, no, no, I don't have to use this anymore. I can now bind the logical units. I can just put them together. But then of course my component was growing a bit and I was like, yeah, how do I actually say that this things belong together? Do we have a comment like start items block and items block? How do I achieve this? So I started to refactor this component a bit, the same template we saw before, but now on top we have two different functions, the use greeting and the use items, which encapsulate all of the functionality in those functions where I have everything related here and return the necessary properties to the outside. And if I scroll down to the setup block, I can now see that it's getting a bit more cleaner if it was getting a bit nasty and I can outsource all of this logic to somewhere else. And here I can clearly see the greeting and full name items and delete items coming from those two composables.
4. Initial Experience with State Management and Vuex
The speaker discusses their initial experience with state management and Vuex. They explain how installing Vuex simplified the process of creating state management and allowed them to focus on more complex aspects of development.
It was also not really discussed. It was just really hidden in the API documentation that there is something like a global root. And then I sat down and thought, okay, state management sounds important, sounds difficult. Store sounds difficult, observables, Vuex, I'm not sure, but I will install Vuex now. And it was really just mind blown how simple this made it for me to create state management by only creating this index.js file. And already I had some state. It was a really powerful tool because it was so simple to use to then focus on the complex parts of writing code or finding solutions for bigger problems.
5. Using Composables for State Management
When starting with Vue 3, I realized I could achieve state management with composables. I wanted to explore the possibilities further. In a code sandbox example, I focused on cart items with a loading state and used the unmounted hook to fetch data. The setup function contained the state, load items function, and methods for deleting items. I then switched to a different alternative of the application, importing the use items composable in the cart items alternative. This approach provided local state management.
But when I was starting with Vue 3, I thought, hey, give me a second. I think I can do achieve state management actually with composable. And it was not because Vue wasn't ready for Vue 3 yet. They were pretty quick and there was a migration guide. But I was interested in what is everything I can actually achieve with composables. I want to get a step further here. And here I have another code sandbox, which will probably load soon. But I think I also have it preloaded here. Yes, I do.
So here I want to focus first on the cart items, which we see here. And now I have a bit more of a realistic example. So if I reload this, you can see that there will actually be like three seconds of a loading time because usually I fetch the items from a server. So I have three seconds of loading and then I see the items. And here I have a first item. So what I have to buy next are the eggs and then I have my list of items and here I really use now a state with a floating where I can set a loading state if it's still loading. And in the script part I additionally use now the unmounted hook where I can fetch the data. So going to the setup function we can now see the state with the items and the loading. And then I have the important function here are the load items where I set isLoading to true. Since I don't actually have a real endpoint that I can talk to I use a useSleep function for three seconds. And then I set some dummy items, my eggs and my milk. And if everything works out I can set isLoading to false again. I also have my method to delete the item and I have a computed property for the first item and I use the unmounted lifecycle hook to load the items as soon as my component has mounted.
Ok, so far so good, we have something looking like a state but it doesn't really feel like state management right away. So now I want to go to the app root component and switch to a different alternative of this application and use now two different components which are both providing us our items. So if I save this and reload, in the meantime I will go to the cart items alternative which is looking pretty similar to the favourites. So they are both just showing our items. So on the cart items alternative, I scroll down and instead of the whole logic we saw beforehand, I can now see that I import the use items composable and I get all of the necessary data from the state load items, first item, delete item and unmounted, I call the load items function. Now I can see here my three seconds loading and I can see two times my list for my items. And here I want you to focus on the local state management, if I open the file, which I thought I had opened before, but I do it again for the composable. I can now see that the state here is outside of the component of this export function.
6. Implementation and State Management
The implementation is the same as before, with the addition of the read-only keyword to create a store-like feeling. The state can be placed inside the exported function, allowing for local state management. However, if global state management is desired, the state can be moved on top of the export. By exporting the function multiple times, the state is created only once and remains global. After installing the dependencies, the X can be deleted twice, demonstrating both loading and global state management.
And the rest of the implementation is the same one as before. It's just copied over with one important difference. So here I import additionally the read-only keyword by view to have this store-like of feeling of this composable, to have the single source of truth what we expect our store should behave like. And now I want to put the state inside of this exported function. And if I am doing this and wait for it to reload here. Ah, come on. They are loading for three seconds. And I have my x, which I can delete in those local state. And here below I can delete the fresh milk on those local state management as both the card items alternative and the favorites are both using this use items, which has the state initialized inside of this function. But if you think, hey, this is kind of weird. This is not what I expect from state management. I expect it to be global. This is achieved by just moving the state on top of the export. And I will reload this again. And then you can see that, therefore, I just created the state now once. It's no global. It doesn't change. We don't initialize it a couple of times. We just export this function a couple of times. So after I installed all of those dependencies, you will see that I can now delete the X and they will be deleted twice. So they are loading and global state management.