Reset application state
Restore a store after a user logs out or a workflow is cleared.
Zustand · Module
getInitialState is an imperative API attached to Zustand stores created with create. It returns the store's initial state, commonly used to implement reset actions.
getInitialState is an API attached to a store created with create. It returns the state captured when the store was initialized, so an action can pass that value to set to restore the store's initial contents.
store.getInitialState()The store's initial state snapshot.
import { create } from 'zustand'
type State = {
count: number
reset: () => void
}
const useStore = create<State>()((set, get, store) => ({
count: 0,
reset: () => set(store.getInitialState()),
}))
useStore.setState({ count: 3 })
useStore.getState().reset()
console.log(useStore.getState().count) // 0The action restores the store by passing its original snapshot to set.
Restore a store after a user logs out or a workflow is cleared.
Provide a reset button or test cleanup action that returns state to its starting snapshot.
getInitialState returns the store's initial state snapshot. For a React store created with create, it is available as an attached API utility alongside setState, getState, and subscribe.
Follow-up: How would you reset a store? Define an action that calls set(store.getInitialState()), or use the store's setState method externally with its initial snapshot.
Inside a state creator, the store argument exposes store APIs. A reset action can call set(store.getInitialState()) to replace the current state with the initial value.
Follow-up: Why put the call inside an action? Store APIs are not safe to call synchronously during initialization, so defer the call until after creation.
The API is attached to the hook returned by create. This means consumers can use the hook for React state and also access imperative APIs such as getInitialState.
Follow-up: What other imperative APIs are attached? The documentation lists setState, getState, getInitialState, and subscribe.
createsetStategetStatesubscribeHow to reset state