Skip to main content
Module

x/valtio/docs/utils/proxyWithComputed.mdx

πŸ’Š Valtio makes proxy-state simple for React and Vanilla
Go to Latest
File
---title: 'proxyWithComputed'section: 'Utils'description: ''---
# 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.
```jsimport { 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](https://github.com/pmndrs/valtio/issues/192).