1. Utils
  2. proxyWithComputed

proxyWithComputed

proxyWithComputed util

You can have computed values with dependency tracking with property access. Dependency tracking in proxyWithComputed conflicts with the work in useSnapshot. React users should prefer using derive. proxyWithComputed works well for some edge cases and for vanilla-js users.

import { proxyWithComputed } from 'valtio/utils'

const state = proxyWithComputed(
  {
    count: 1,
  },
  {
    doubled: (snap) => snap.count * 2,
  }
)

// Computed values accept custom setters too:
const state2 = proxyWithComputed(
  {
    firstName: 'Alec',
    lastName: 'Baldwin',
  },
  {
    fullName: {
      get: (snap) => snap.firstName + ' ' + snap.lastName,
      set: (state, newValue) => {
        ;[state.firstName, state.lastName] = newValue.split(' ')
      },
    },
  }
)

// if you want a computed value to derive from another computed, you must declare the dependency first:
const state = proxyWithComputed(
  {
    count: 1,
  },
  {
    doubled: (snap) => snap.count * 2,
    quadrupled: (snap) => snap.doubled * 2,
  }
)

The last use case fails to infer types in TypeScript #192.