loading...
Cover image for You Might Not Need Vuex with Vue 3

You Might Not Need Vuex with Vue 3

blacksonic profile image Gábor Soós ・3 min read

Byte-sized Vue 3 (2 Part Series)

1) The Vue 3 upgrade guide 2) You Might Not Need Vuex with Vue 3

Vuex is an awesome state management library. It's simple and integrates well with Vue. Why would anyone leave Vuex? The reason can be that the upcoming Vue 3 release exposes the underlying reactivity system and introduces new ways of how you can structure your application. The new reactivity system is so powerful that it can be used for centralized state management.

Do You need a shared state?

There are circumstances when data flow between multiple components becomes so hard that you need centralized state management. These circumstances include:

  • Multiple components that use the same data
  • Multiple roots with data access
  • Deep nesting of components

If none of the above cases are true, the answer is easy, whether you need it or not. You don't need it.

But what about if you have one of these cases? The straightforward answer would be to use Vuex. It's a battle-tested solution and does a decent job.

But what if you don't want to add another dependency or find the setup overly complicated? The new Vue 3 version, together with the Composition API can solve these problems with its built-in methods.

The new solution

A shared state must fit two criteria:

  • reactivity: when the state changes, the components using them should update also
  • availability: the state can be accessed in any of the components

Reactivity

Vue 3 exposes its reactivity system through numerous functions. You can create a reactive variable with the reactive function (an alternative would be the ref function).

import { reactive } from 'vue';

export const state = reactive({ counter: 0 });

The object returned from the reactive function is a Proxy object that can track changes on its properties. When used in a component's template, the component re-renders itself whenever the reactive value changes.

<template>
  <div>{{ state.counter }}</div>
  <button type="button" @click="state.counter++">Increment</button>
</template>

<script>
  import { reactive } from 'vue';

  export default {
    setup() {
      const state = reactive({ counter: 0 });
      return { state };
    }
  };
</script>

Availability

The above example is excellent for a single component, but other components can't access the state. To overcome this, you can make any value available inside a Vue 3 application with the provide and inject methods.

import { reactive, provide, inject } from 'vue';

export const stateSymbol = Symbol('state');
export const createState = () => reactive({ counter: 0 });

export const useState = () => inject(stateSymbol);
export const provideState = () => provide(
  stateSymbol, 
  createState()
);

When you pass a Symbol as key and a value to the provide method, that value will be available for any child component through the inject method. The key is using the same Symbol name when providing and retrieving the value.

provide inject

This way, if you provide the value on the uppermost component, it'll be available in all the components. Alternatively, you can also call provide on the main application instance.

import { createApp, reactive } from 'vue';
import App from './App.vue';
import { stateSymbol, createState } from './store';

const app = createApp(App);
app.provide(stateSymbol, createState());
app.mount('#app');
<script>
  import { useState } from './state';

  export default {
    setup() {
      return { state: useState() };
    }
  };
</script>

Making it robust

The above solution works but has a drawback: you don't know who modifies what. The state can be changed directly, and there is no restriction.

You can make your state protected by wrapping it with the readonly function. It covers the passed variable in a Proxy object that prevents any modification (emits a warning when you try it). The mutations can be handled by separate functions that have access to the writable store.

import { reactive, readonly } from 'vue';

export const createStore = () => {
  const state = reactive({ counter: 0 });
  const increment = () => state.counter++;

  return { increment, state: readonly(state) };
}

The outside world will have access only to a readonly state, and only the exported functions can modify the writable state.

By protecting the state from unwanted modifications, the new solution is relatively close to Vuex.

Summary

By using the reactivity system and the dependency injection mechanism of Vue 3, we've gone from a local state to centralized state management that can replace Vuex in smaller applications.

We have a state object that is readonly and is reactive to changes in templates. The state can only be modified through specific methods like actions/mutations in Vuex. You can define additional getters with the computed function.

Vuex has more features like module handling, but sometimes we don't need that.

If You want to have a look at Vue 3 and try out this state management approach, take a look at my Vue 3 playground.

GitHub logo blacksonic / vue-3-playground

Vue 3 Playground packed with all the new features

Byte-sized Vue 3 (2 Part Series)

1) The Vue 3 upgrade guide 2) You Might Not Need Vuex with Vue 3

Posted on by:

blacksonic profile

Gábor Soós

@blacksonic

Enthusiastic full-stack JavaScript developer/lead, tech writer, speaker at Emarsys

Discussion

markdown guide
 

Hey,

Nice article!

I've been investigating similar functionality recently, and wrapped up shared stores into a class-based format, that works in Vue 2, 3 and Nuxt and supports state, getters, watches, actions (methods) and inheritance:

github.com/davestewart/vue-class-s...

The library is a single decorator that allows you to use a single interface (classes) and returns you a working store in Vue 2 (as a new Vue) or Vue 3 (using the Reactivity API).

Check the docs for provide/inject example and demos for working code:

github.com/davestewart/vue-class-s...

 

Nice work, looks amazing 👍

One idea: add an example on how to use it as a plugin...or publish a plugin also in the package

 

Thanks! Can you expand on that?

Just an example on the Readme on how to use it with the app instances use method. app.use(store)

There's no use per-se, you just create the models and use them where you need them.

If you want a "global" style example, either import as needed or use inject exactly as you have (example code in the README):

github.com/davestewart/vue-class-s...

 

What is the benefit of provide/inject compared to directly import { state } ?

 

The second import solution creates a tightly coupled store, which makes testing, using another store with the same interface, using different stores in different parts of the application hard.

Both solutions work. The second one is simpler but hardly coupled to the implementation. The first one is a bit more complex but makes the code more open to alteration.

 

Vue2 (2.6+) supports similar functionality via Observable.
The downside of switching to alternatives for managing state is the loss of ability to easily debug with the Vue browser extension (the vuex tab specifically). I would caution against using this large scale apps with multiple people working on it, since the conventions around vuex make team and large/long-term dev easier, but for simple apps, I think vuex can easily be replaced with something that may have a simpler learning curve.

 

Yes, the pro of using existing well-known tools are conventions and that people know it. You can come up with your own conventions and integrate it with Vue devtools also, but yes, it's extra work.

 

That's pretty sweet! Simpler than Vuex.

I think I'll use provide and inject for simple states, it's perfect.

But how can we do a cache system like vuex persist?

 

I would use the watchEffect function for persistence.

 

It's more simple until you trip up on something and waste your time going down rabbit-holes.

 

Trip up on what? It's the built-in reactivity system with functions mutating the variables.

I was talking about the simple implementation of trying to replace Vuex, it's not a complete solution. Still it is a nice write up on how one would go about using a simple reactive global store.

 

Hello, is there any real-world practical example for this ? I'm struggling with non-opinionated approach, so there might be a convenience way of adopting this approach

 

I haven't done any official project with this approach, but it was completely fine for a TodoMVC app. If you go down this way you can take general convenience ways from vuex and create your own.