proxySet
Reasoning
Native Sets
store their data in internal slots which are not observable. This means that valtio
cannot track changes to the data inside of a native Set
. proxySet
is a utility that allows you to create a proxy that mimics the behavior of a Set
while still allowing valtio to track changes to the data.
When to use proxySet
proxySet
is useful when you need the functionality of a Set
but still want to track changes to the data. proxySet
can be useful if you're wanting to store unique values or if you want to perform mathematical Set
operations on the data, such as union, intersection, or difference. proxySet
supports all of the new methods introduced to Set
:
intersection
isDisjointFrom
isSubsetOf
isSupersetOf
symmetricDifference
union
You can see a full list of the methods supported by proxySet
in the MDN documentation.
If your data can be represented as a simple array or object, and you have no need for the additional functionality provided by proxySet
, you should use proxy
with a simple array or object instead. It is more performant and easier to use.
Use a js Set
with Valtio
This utility creates a proxy which mimics the native Set
behavior. The API is the same as the native Set
API.
import { proxySet } from 'valtio/utils'
const state = proxySet([1, 2, 3])
state.add(4)
state.delete(1)
state.forEach((v) => console.log(v)) // ---> 2,3,4
Nesting
It can be used inside a proxy
as well.
import { proxySet } from 'valtio/utils'
const state = proxy({
count: 1,
set: proxySet(),
})