How to reset state
In some cases, you might want to reset the state in your proxy instance to its initial values. For example, you are storing form values or some other ephemeral UI state that you want to reset. It turns out this is quite simple to do!
const initialObj = {
text: 'hello',
arr: [1, 2, 3],
obj: { a: 'b' },
}
const state = proxy(initialObj)
const reset = () => {
const resetObj = _.cloneDeep(initialObj)
Object.keys(resetObj).forEach((key) => {
state[key] = resetObj[key]
})
}
Note that we're using the cloneDeep utility function from lodash
to copy the initial object in the reset
function. This allows Valtio to update correctly when the value of a key is an object. If you prefer underscore
or some similar JS utility library, feel free to use that instead.
Alternatively, you can store the object in another object, which make the reset logic easier:
const state = proxy({ obj: initialObj })
const reset = () => {
state.obj = _.cloneDeep(initialObj)
}
[!NOTE] Using
structuredClone()
In 2022, there was a new global function added called structuredClone
that is widely available in most modern browsers. While this function and _.cloneDeep
from lodash seem to do the same thing, their implementations are quite different.
In valtio v1, proxy
cloned the object used for inital state under the hood. Because the original object isn't used, structuredClone
works just fine as a drop in replacement for _.cloneDeep
.
// v1
const initialObj = {...}
const state = proxy({ obj: initialObj })
const reset = () => {
state.obj = structuredClone(initialObj)
}
In valtio v2, the proxy
function no longer clones the initial state. Instead, it uses the original object directly. This means that structuredClone
is no longer a drop in replacement for _.cloneDeep
and will throw an error. To fix this, you can use structuredClone
to clone the initial state that you pass to into proxy
.
// v2
const initialObj = {...}
const state = proxy(structuredClone(initialObj))
const reset = () => {
state.obj = structuredClone(initialObj)
}