proxyMap
Reasoning
Native Maps store their data in internal slots which are not observable. This means that valtio cannot track changes to the data inside of a native Map. proxyMap is a utility that allows you to create a proxy that mimics the behavior of a Map while still allowing valtio to track changes to the data.
When to use proxyMap
proxyMap is useful when you need the flexibility of a Map but still want to track changes to the data. It can be useful if you don't know the structure of the data you'll be working with and this data may have non-primitive values as keys (e.g. objects, arrays, etc.). In this case, you can use proxyMap to create a proxy that mimics the behavior of a Map while still allowing valtio to track changes to the data. If your data can be represented as a simple object, you should use proxy with a simple object instead. It is more performant and easier to use.
Use a js Map with Valtio
This utility creates a proxy which mimics the native Map behavior. The API is the same as the Map API.
import { proxyMap } from 'valtio/utils'
const state = proxyMap()
state.size // ---> 0
state.set(1, 'hello')
state.size // ---> 1
state.delete(1)
state.size // ---> 0
Nesting
It can be used inside a proxy as well.
import { proxyMap } from 'valtio/utils'
const state = proxy({
count: 1,
map: proxyMap(),
})
When using an object as a key, you can wrap it with ref so it's not proxied. This is useful if you want to preserve the key equality
import { proxyMap } from 'valtio/utils'
// with ref
const key = ref({})
state.set(key, 'hello')
state.get(key) //hello
// without ref
const key = {}
state.set(key, 'value')
state.get(key) //undefined
isProxyMap
If you want to check if an object is a proxyMap, you can use the isProxyMap function.
import { proxy, ref } from 'valtio'
import { proxyMap, isProxyMap } from 'valtio/utils'
const state = proxy({
nativeMap: ref(new Map(/*...*/)),
proxyMap: proxyMap(),
})
isProxyMap(state.nativeMap) // false
isProxyMap(state.proxyMap) // true