1. Utils
  2. derive

derive

create a new proxy derived from others

You can subscribe to some proxies using get to create snapshots used to compute new values.

import { derive } from 'valtio/utils'

// create a base proxy
const state = proxy({
  count: 1,
})

// create a derived proxy
const derived = derive({
  doubled: (get) => get(state).count * 2,
})

// alternatively, attach derived properties to an existing proxy
derive(
  {
    tripled: (get) => get(state).count * 3,
  },
  {
    proxy: state,
  }
)

underive

stop evaluating

In some cases you may want to unsubscribe after deriving a proxy. To do so, use the underive util. You may also pass keys to indicate which properties you want to unsubscribe. If you specify delete option, it will delete the properties and you can attach new derived properties.

import { derive, underive } from 'valtio/utils'
const state = proxy({
  count: 1,
})

const derivedState = derive({
  doubled: (get) => get(state).count * 2,
})

underive(derivedState)