Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pinia store vs composable functions

I would like to figure out what are the advantages of using Pinia store instead of using just pure ts composable functions like

const userName = ref('')

export default function useUser() {

  const setUserName(name: string) => {
    userName.value = name
  }

  return {
    userName: readonly(userName),
    setUserName
  }

}

and then usage


const {userName, setUserName} = useUser()

Because, for example here in this Vitesse example https://github.com/antfu/vitesse/blob/main/src/stores/user.ts, the Pinia usage looks very similar.

Thanks for clarifying :)

like image 396
Petr Klein Avatar asked Sep 12 '25 16:09

Petr Klein


1 Answers

I found this explanation, and it makes sense to me:

I feel like you may be missing the point of Composables and the Composition API a bit - they are useful as a way of organising your code "feature-first", rather than "component-first" (literally, throught composition). This means that Composables are shared functionality, not state.

Certain functionalities may include internal (shared, app-wide) state, but that isn't the purpose of Composables per se. Pinia, on the other hand, is meant for sharing state exclusively. It may include functionality to manage said state, but it doesn't exist without that shared state.

A good place to see this "in action" is Vue Use, a set of common-use composables. Some may include internal state, but most do not, so that only augment a component's functionality, perhaps adding some local state (as opposed to global, shared state)

Source: https://www.reddit.com/r/vuejs/comments/t88xzy/comment/hzmoet2/?utm_source=share&utm_medium=web2x&context=3

like image 154
Matthew Avatar answered Sep 15 '25 06:09

Matthew