Introduce
Have you ever thought about trying to use global state instead of Stores?
I have an example as follows, I will create 1 composable continue to import ref email into 2 components and try to change the value of ref from component A to see how it reacts
As you can see, when A makes a change, there will be a change for everyone, why is that?
The concept of Global state ?
First we re-read the composable document about State Management with Reactivity API , I will quote a small note here:
Although here we are using a single reactive object as a store, you can also share reactive state created using other Reactivity APIs such as ref() or computed(), or even return global state from a Composable
Example of global and local part of a composable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { ref } from 'vue' // global state, created in module scope const globalCount = ref(1) export function useCount() { // local state, created per-component const localCount = ref(1) return { globalCount, localCount } } |
Defect
- Difficult to manage global state: If you are confident that you are a good state manager and will maintain the project well, then I think this part can be skipped.
- Mutation strictness : Having state disorder when there are many changes in many components this you can avoid by wrapping read only for the ref to avoid this problem
- Cross-Request State Pollution when SSR :
- No Vue DevTools support : Honestly, mostly we don’t use devtools very often, right?
As you can see the disadvantages on the thing that I countered by bypassing it and trying to use it, it doesn’t look good at all. Use Pinia instead because these disadvantages are well supported by Pinia, so when will we use global state
Conclusion :
Use global state only if that function has low impact and is not global in all pages, but only some pages or components, global state should only have readonly attribute to avoid Mutation strictness
Through the above article, I hope to help you better understand the global state to avoid unexpected situations in the future.