头图

Comparison of Pinia and Vuex: Is Pinia a good alternative to Vuex?

杜尼卜
中文

Introduction

Pinia is a lightweight state management library for Vue.js, which has become very popular recently. It uses the new reaction system in Vue 3 to build an intuitive and fully typed state management library.

Pinia's success can be attributed to its unique capabilities for managing stored data (scalability, storage module organization, state change grouping, multiple storage creation, etc.).

On the other hand, Vuex is also a popular state management library built for the Vue framework, and it is also a state management library recommended by the Vue core team. Vuex pays great attention to the scalability of the application, the ergonomics and confidence of the developers. It is based on the same traffic architecture as Redux.

In this article, we will compare Pinia and Vuex. We will analyze the settings, community advantages and performance of these two frameworks. We will also look at the new changes in Vuex 5 compared to Pinea 2.

Set up

Pinia settings

Pinia is easy to get started because it only needs to install and create a store.

To install Pinia, you can run the following command in the terminal:

yarn add pinia@next
# or with npm
npm install pinia@next

This version is compatible with Vue 3. If you are looking for a version compatible with Vue 2.x, please check the v1 branch.

Pinia is a wrapper around the Vue 3 Composition API. Therefore, you don't need to initialize it as a plugin, unless you need Vue devtools support, SSR support, and webpack code splitting:

//app.js
import { createPinia } from 'pinia'
app.use(createPinia())

In the above snippet, you add Pinia to the Vue.js project so that you can use Pinia's global objects in your code.

defineStore method with an object containing the states, actions, and getters needed to create a basic store.

// stores/todo.js
import { defineStore } from 'pinia'

export const useTodoStore = defineStore({
  id: 'todo',
  state: () => ({ count: 0, title: "Cook noodles", done:false })
})

Vuex settings

Vuex is also very easy to set up, requiring installation and creation of a store.

To install Vuex, you can execute the following command in the terminal:

npm install vuex@next --save
# or with yarn
yarn add vuex@next --save

createStore method with an object containing the states, actions, and getters needed to create the basic store:

//store.js
import {createStore} from 'vuex'
const useStore = createStore({
  state: {
    todos: [
      { id: 1, title: '...', done: true }
    ]
  },
  getters: {
    doneTodos (state) {
      return state.todos.filter(todo => todo.done)
    }
  }
})

To access Vuex global objects, you need to add Vuex to the Vue.js project root file, as shown below:

//index.js
import { createApp } from 'vue'
import App from './App.vue'
import {useStore} from './store'
createApp(App).use(store).mount('#app')

use

Pinia use

Using Pinia, you can access the store as follows:

export default defineComponent({
  setup() {
    const todo = useTodoStore()

    return {
      // 只允许访问特定的state
      state: computed(() => todo.title),
    }
  },
})

state object of store is omitted when accessing its attributes.

Vuex use

Using Vuex, you can access the store as follows:

import { computed } from 'vue'
export default {
  setup () {
    const store = useStore()

    return {
      // 访问计算函数中的状态
      count: computed(() => store.state.count),

      // 访问计算函数中的getter
      double: computed(() => store.getters.double)
    }
  }
}

The power of communities and ecosystems

At the time of writing this article, Pinia's community is small, which leads to very few contributions on Stack Overflow and few solutions.

Since Pinia became popular at the beginning of last year and is currently making progress, its community is growing rapidly. Hope that more contributors and solutions will appear on Pinia soon.

Vuex is a state management library recommended by the Vue.js core team. It has a huge community and core team members have made significant contributions. It is easy to find solutions to Vuex errors on Stack Overflow.

Learning curve and documentation

Both state management libraries are fairly easy to learn because they have good documentation and learning resources on YouTube and third-party blogs. For developers who have previous experience in using Flux architecture libraries such as Redux, MobX, and Recoil, their learning curve is easier.

The documentation for both libraries is great and written in a way that is friendly to both experienced developers and new developers.

GitHub ratings

At the time of writing, Pania has two major versions: v1 and v2, of which v2 has more than 1.6k stars on GitHub. Given that it was originally released in 2019 and is relatively new, it is undoubtedly one of the fastest growing state management libraries in the Vue.js ecosystem.

At the same time, five stable versions of the Vuex library have been released since the creation of Vuex. Although v5 is in the experimental stage, Vuex's v4 is by far the most stable version, with approximately 26.3k stars on GitHub.

performance

Both Pinia and Vuex are very fast, and in some cases, web applications using Pinia will be faster than using Vuex. This performance improvement can be attributed to Pinia's extremely light weight, which is about 1KB in size.

Although Pinia was built with the support of Vue devtools, some functions such as time travel and editing are still not supported because Vue devtools does not expose the necessary API. This is worth noting when development speed and debugging are more important to your project.

Compare Pinia 2 and Vuex 4

Pinia compares these to Vuex 3 and 4:

  • The mutation no longer exists. They are often considered very verbose. They initially brought devtools integration, but this is no longer a problem.
  • There is no need to create a custom complex wrapper to support TypeScript, everything is typed, and the API is designed to make use of TS type inference as much as possible.

These are the additional insights Pinia made in the comparison between its state management library and Vuex:

  • Pinia does not support nested storage. Instead, it allows you to create stores as needed. However, stores can still be implicitly nested by importing and using stores in another store
  • The memory is automatically named when it is defined. Therefore, there is no need to explicitly name the module.
  • Pinia allows you to create multiple stores and let your bundler code automatically split them
  • Pinia allows getters to be used in other getters
  • Pinia allows the use of $patch to group changes on the devtools timeline.
this.$patch((state) => {
  state.posts.push(post)
  state.user.postsCount++
}).catch(error){
  this.errors.push(error)
}

Comparing Pinia 2 (currently in alpha stage) with Vuex, we can infer that Pinia is ahead of Vuex 4.

The Vue.js core team has developed an open RFC for Vuex 5, similar to the RFC used by Pinia. Currently, Vuex collects as much feedback from the community as possible through RFC. Hope that the stable version of Vuex 5 can surpass Pinea 2.

According to the creator of Pinia (Eduardo San Martin Morote) who is also a member of the Vue.js core team and actively involved in the design of Vuex, Pania and Vuex have more similarities than differences:

Pinia tries to get as close as possible to Vuex's philosophy. It was designed to test the next iteration of Vuex's proposal, and it was successful because we currently have an open RFC for Vuex 5, and its API is very similar to the one used by Pinea. My personal intention for this project is to redesign the experience of using the global store while maintaining the approachable concept of Vue. I keep Pinea's API as close as Vuex because it continues to move forward, making it easy for people to migrate to Vuex, and even merge the two projects (under Vuex) in the future.

Although Pinia is sufficient to replace Vuex, it is not its goal to replace Vuex, so Vuex is still the recommended state management library for Vue.js applications.

Advantages and disadvantages of Vuex and Pinia

Advantages of Vuex

  • Support debugging functions such as time travel and editing
  • Suitable for large, high-complexity Vue.js projects

Disadvantages of Vuex

  • Starting from Vue 3, the result of the getter will not be cached like a calculated property
  • Vuex 4 has some issues related to type safety

Advantages of Pinia

  • Full TypeScript support: Compared to adding TypeScript in Vuex, adding TypeScript is easier
  • Extremely lightweight (about 1KB in size)
  • The store's action is scheduled as a regular function call, instead of using the dispatch method or the MapAction auxiliary function, which is very common in Vuex
  • Support multiple stores
  • Support Vue devtools, SSR and webpack code splitting

Disadvantages of Pinia

  • Does not support debugging functions such as time travel and editing

When to use Pinia and when to use Vuex

According to my personal experience, since Pinea is lightweight and small in size, it is suitable for small and medium-sized applications. It is also suitable for low-complexity Vue.js projects, because some debugging features such as time travel and editing are still not supported.

Using Vuex for small and medium-sized Vue.js projects is excessive because it is heavyweight and has a great impact on performance degradation. Therefore, Vuex is suitable for large-scale, high-complexity Vue.js projects.

阅读 3.7k

前端全栈开发者
专栏首发于公众号《前端全栈开发者》,订阅关注第一时间阅读好文

做工程师不做码农、全栈开发工程师、持续学习者

11.2k 声望
5.6k 粉丝
0 条评论
你知道吗?

做工程师不做码农、全栈开发工程师、持续学习者

11.2k 声望
5.6k 粉丝
文章目录
宣传栏