Clear session state
A user signs out and application state must return to its original values.
Zustand · Const
Add a reset action that calls set(store.getInitialState()) to restore a Zustand store's initial state. For multiple stores, register reset callbacks and invoke them together.
The documented pattern adds a reset action inside the store creator and calls set with store.getInitialState(). This restores the store's original state on demand. For several stores, keep reset callbacks in a shared Set and invoke each callback when a global reset is needed.
reset: () => {
set(store.getInitialState())
}| Name | Type | Description |
|---|---|---|
store | Store API | The store's state creator receives set, get, and store; the reset pattern uses the store API's getInitialState method. |
A reset action returns void; invoking it restores the store to its initial state.
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: 5 })
useStore.getState().reset()
console.log(useStore.getState().count) // 0The store exposes a reset action that replaces its current values with the initial snapshot returned by the store API.
A user signs out and application state must return to its original values.
A test suite needs a reusable mechanism to return stores to their baseline.
An application has several independent stores that must be cleared together.
Define reset on the store and implement it with set(store.getInitialState()). The store API supplies the initial snapshot, so the action does not need to duplicate the initial values.
Follow-up: How would you reset every store? Register a callback for each store in a shared Set, then iterate through that Set and call each callback.
Create each store through a wrapper around the real create function. After creation, add a callback that invokes store.setState with the store's initial state and replacement enabled.
Follow-up: Why use a Set? It provides a central collection of reset callbacks that can be iterated whenever the application needs a global reset.
The reset action is placed in the store definition and can be called from application code like any other action. It restores the values captured as the store's initial state.
Follow-up: What should be checked when adding new stores? Ensure they are created through the wrapper; otherwise their reset callback will not be registered.
createsetgetInitialStatesetStateStateCreator