Utilizing proxies to detect mutations and create an immutable state
Valtio creates immutable objects from mutable objects with proxies. We call the immutable object a snapshot.
To create a mutable object wrapped in a proxy object, we use the proxy
function exported by Valtio.
The following example is to create an object with a count
property:
import { proxy } from "valtio"; const state = proxy({ count: 0 });
The state
object returned by the proxy
function is a proxy object that detects mutations. This allows you to create an immutable object.
To create an immutable object, we use the snapshot
function exported by Valtio, as follows:
import { snapshot } from "valtio"; const snap1 = snapshot(state);
Though the state
variable is { count: 0 }
and the snap1
variable is { count: 0 }
, state
and snap1
have different references. state
is a mutable object wrapped in a proxy, whereas snap1
is an immutable object frozen with Object.freeze
(https://developer...