Performance: Persisting store state
This concept affects page load speed and interaction responsiveness by managing how store data is saved and restored across sessions.
import { createStore } from 'vuex'; const store = createStore({ state() { return { count: 0 }; }, mutations: { increment(state) { state.count++; } }, plugins: [store => { const savedCount = localStorage.getItem('count'); if (savedCount) { store.replaceState({ count: JSON.parse(savedCount) }); } window.addEventListener('beforeunload', () => { localStorage.setItem('count', JSON.stringify(store.state.count)); }); }] });
import { createStore } from 'vuex'; const store = createStore({ state() { return { count: 0 }; }, mutations: { increment(state) { state.count++; localStorage.setItem('count', JSON.stringify(state.count)); } }, plugins: [store => { const savedCount = localStorage.getItem('count'); if (savedCount) { store.replaceState({ count: JSON.parse(savedCount) }); } }] });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Saving state on every mutation synchronously | Minimal | Multiple reflows on load | High due to blocking | [X] Bad |
| Load once on startup, save on unload | Minimal | Single reflow | Low blocking | [OK] Good |
vuex-persistedstate plugin to a Vuex store?vuex-persistedstate plugin is imported as a function and added inside the plugins array when creating the store.createPersistedState() inside the plugins array.vuex-persistedstate:
import { createStore } from 'vuex';
import createPersistedState from 'vuex-persistedstate';
const store = createStore({
state() {
return { count: 0 };
},
mutations: {
increment(state) {
state.count++;
}
},
plugins: [createPersistedState()]
});
store.commit('increment');
// After page reload, what is the value of store.state.count?increment increases count from 0 to 1.count still 1.vuex-persistedstate to your Vuex store but the state is not saved after refresh. Which of these is the most likely cause?user part of your Vuex state and store it in sessionStorage instead of localStorage. Which is the correct way to configure vuex-persistedstate?paths option specifies which parts of the state to save, so paths: ['user'] is correct.storage option expects the storage object, so window.sessionStorage is correct.Pass the test and this pattern moves unknown