Introduction

There’s been a lot of discussion about state management in the upcoming Vue 3 framework. Some writers go as far as declaring Vuex dead. Reactivity is all we need, is the claim. Just like blockchain was supposed to cure all problems of modern civilization ;-) Jokes aside, it does look like an intriguing possibility, so we’ve taken a challenge and explored it in this article.

TL;DR

Vue 3 Reactivity System, now free of UI confines, can be efficiently employed as a powerful tool to handle state. This requires extra plumbing though, with no batteries included. If you want to get straight to technical details, scroll down to Reactive proposal for application state chapter below.

The source code for the article can be found at https://bitbucket.org/letsdebugit/vue-3-state. It uses the simple build-less architecture presented in my recent article about Vue JS 3 Application Without Build.

No Need for Vuex?

I’ve seen many brilliant proposals for managing state using Vue 3 reactivity system. Some would end with a bold conclusion: Vuex is no longer needed. On closer inspection I wasn’t so sure. However ingenious, many proposals are essentially just another singleton with a bunch of methods, only made reactive. In all fairness this was perfectly doable with Vue 2 - yet we kept using Vuex. Why? Because there are deeper reasons why we got Vuex, Redux etc. Allow me now to stir a controversy:

A singleton with a bunch of methods is not a replacement for Vuex, even if it’s reactive.

What Makes a Good Application State?

A viable solution for application state must include the following:

  • Centralized state available to all components. We used to call it a store.
  • Functions to safely modify the state, routinely called mutations.
  • Ability to modify state in async functions such as API calls. Vuex makes it possible through actions, Redux offers thunks.
  • Prevent programmer from shooting himself in the foot by modifying state directly.

It is the last requirement which lacks in majority of the proposals. And for me it is a crucial requirement.

All the effort of writing proper state and mutations is waste of time, if my colleagues are free to modify and hack state directly, causing inconsistencies and elusive bugs.

Vuex helps enforce this with strict mode, which throws exceptions on attempts to illegally alter the state. Redux resorts to immutability - any local alterations will simply be discarded with the next mutation cycle.

Finally, the mere fact of using Vuex (or Redux etc.) enforces structure and discipline. It does come with the inevitable boilerplate code. But then one simply has to follow the structure - design a state store, define state mutations, organize application logic into actions, create state getters when state gets complex etc.

#javascript #web development #design pattens #vuejs #vue #state management #web application architecture

Reactive Vue 3 State
3.00 GEEK