How to reset Vuex state

Resetting Vuex state is essential for user logout, form clearing, and returning the application to its initial state. As the creator of CoreUI with 25 years of development experience, I’ve implemented state reset functionality in numerous Vue.js enterprise applications. The most effective approach creates a dedicated reset mutation that restores state to initial values using a stored reference. This method ensures clean state management while maintaining predictable application behavior.

Create a reset mutation that restores state to its initial values using Object.assign.

// store/index.js
const initialState = {
  user: null,
  cart: [],
  notifications: [],
  preferences: {
    theme: 'light',
    language: 'en'
  }
}

const store = createStore({
  state: () => ({ ...initialState }),

  mutations: {
    RESET_STATE(state) {
      Object.assign(state, initialState)
    },
    SET_USER(state, user) {
      state.user = user
    },
    ADD_TO_CART(state, item) {
      state.cart.push(item)
    }
  },

  actions: {
    resetStore({ commit }) {
      commit('RESET_STATE')
    },
    logout({ commit }) {
      commit('RESET_STATE')
      // Additional logout logic
    }
  }
})

// Usage in component
export default {
  methods: {
    handleLogout() {
      this.$store.dispatch('logout')
    },
    clearForm() {
      this.$store.commit('RESET_STATE')
    }
  }
}

This implementation stores the initial state as a reference object and uses Object.assign() to replace the current state with initial values. The reset action provides a clean interface for components to trigger state reset, while maintaining the reactivity of all state properties. This pattern works with nested objects and arrays.

Best Practice Note:

This is the same state reset pattern we use in CoreUI Vue applications for reliable state management. Consider creating module-specific reset mutations for larger applications with multiple Vuex modules to maintain granular control over state resets.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author