How to Reset State
In many applications, you need a way to reset state back to its initial values, such as when clearing a form or logging out a user.
The Reset Pattern
The most straightforward way to reset a Valtio proxy is to re-apply the initial state. It's important to not reassign the proxy object itself, but rather to mutate its properties back to their original values.
- Store your initial state in a constant.
- Create a
resetfunction that iterates over the initial state and reassigns each property on the proxy.
import { proxy } from 'valtio';
import { deepClone } from 'valtio/utils';
const initialState = {
text: 'hello',
arr: [1, 2, 3],
obj: { a: 'b' },
};
// Create the state from a deep clone of the initial state
const state = proxy(deepClone(initialState));
const reset = () => {
const resetState = deepClone(initialState);
Object.keys(resetState).forEach((key) => {
state[key] = resetState[key];
});
};
Note on deepClone: Since Valtio v2, proxy() no longer clones the initial object. It's crucial to use deepClone() from valtio/utils to prevent both the state and initialState variables from pointing to the same mutable object.
An Alternative Pattern
An even simpler approach is to nest your state inside a single property. This makes the reset operation a single assignment.
import { proxy } from 'valtio';
import { deepClone } from 'valtio/utils';
const initialState = { text: 'hello' };
const state = proxy({ data: deepClone(initialState) });
const reset = () => {
state.data = deepClone(initialState);
};
A Note on structuredClone()
Modern JavaScript environments provide a global structuredClone() function. While you can use it instead of deepClone(), be aware that structuredClone does not preserve ref() objects. deepClone from valtio/utils is ref-aware and is the recommended choice for cloning Valtio state.