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!

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. It is not recommended that you reuse the object that you pass into the proxy function. If you use structuredClone that object, it will throw an error. _.cloneDeep won't give you an error, but it could produce unwatned results. To fix this, you can clone the intial state object that you pass to into proxy. You can do this with _.cloneDeep, structuredClone, or the utility function deepClone from valtio/utils. Example below.

// v2
const initialObj = {...}

const state = proxy(structuredClone(initialObj))

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

See also title: 'How to Migrate to v2 from v1'.