1. How to reset state

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!

import { proxy } from 'valtio'
import { deepClone } from 'valtio/utils'

const initialObj = {
  text: 'hello',
  arr: [1, 2, 3],
  obj: { a: 'b' },
}

const state = proxy(deepClone(initialObj))

const reset = () => {
  const resetObj = deepClone(initialObj)
  Object.keys(resetObj).forEach((key) => {
    state[key] = resetObj[key]
  })
}

Note that we're using the deepClone() utility function from valtio/utils to copy the initial object in both the reset function and the state proxy. Using deepClone in the proxy function is a new requirement in v2. Valtio no longer clones the initial state by default. If you reuse the object you pass into the proxy function, you may get unexpected results.

Alternatively, you can store the object in another object, which make the reset logic easier:

const state = proxy({ obj: initialObj })

const reset = () => {
  state.obj = deepClone(initialObj)
}

[!NOTE] Using structuredClone()

In 2022, there was a new global function added called structuredClone that is widely available in most modern browsers. You can use structuredClone in the same way as deepClone above, however deepClone is preferred as it will be aware of any refs in your state.