Session cleanup
Clear application state after a user signs out.
Zustand · Const
Add a reset action that applies the store’s captured initial state. For multiple stores, collect reset callbacks and invoke them together.
Define a reset action inside the store creator and call set(store.getInitialState()). Zustand supplies the store API as the third creator argument, allowing the action to retrieve and apply the store’s initial state.
reset: () => set(store.getInitialState())| Name | Type | Description |
|---|---|---|
store | StoreApi<State> | Zustand state creator callback; its third argument provides the store API used to call getInitialState(). |
A reset action that updates the store to its initial state; the guide does not specify a separate return value.
store as its third argument, alongside set and get.getInitialState() on the store API and pass the result to set to perform the reset.true replaces the entire state rather than shallow-merging it.import { create } from 'zustand'
type State = {
count: number
reset: () => void
}
const useCounter = create<State>()((set, get, store) => ({
count: 0,
reset: () => set(store.getInitialState()),
}))
useCounter.setState({ count: 3 })
useCounter.getState().reset()
console.log(useCounter.getState().count) // 0The action restores the store to the initial state captured by Zustand.
Clear application state after a user signs out.
Return a form or wizard store to its starting values.
Restore every store between test cases.
Add a reset action to the store and implement it with set(store.getInitialState()). The store API is available as the third argument to the state creator.
Follow-up: How would you reset several stores? Create a shared collection of reset callbacks, register one for each store, and invoke every callback when a global reset is needed.
Use store.getInitialState() to obtain the state captured when the store was created, then apply it with set. This keeps the reset target tied to the store’s own initial value.
Follow-up: Why might replacement mode be preferable for a global reset? It removes any state keys added later instead of retaining them through a shallow merge.
For a group of stores, register callbacks in a shared Set. Each callback can call store.setState(store.getInitialState(), true), and a coordinator can execute the set.
Follow-up: How can this pattern support tests? Run the collected callbacks after each test so stores return to their initial state.
createsetgetgetInitialStatesetStateStateCreator