Using proxies to optimize re-renders
Valtio uses proxies to optimize re-renders, as well as detecting mutations. This is the pattern of optimizing re-renders we learned about in the Detecting property access section of Chapter 6, Introducing Global State Libraries.
Let's learn about the usage and behavior of Valtio hooks with a counter app. The hook is called useSnapshot
. The implementation of useSnapshot
is based on the snapshot
function and another proxy to wrap it. This snapshot
proxy has a different purpose from the proxy used in the proxy
function. The snapshot
proxy is used to detect the property access of a snapshot object. We will see how render optimization works, thanks to the snapshot
proxy.
We start with importing functions from Valtio to create a counter app:
import { proxy, useSnapshot } from "valtio";
proxy
and useSnapshot
are two main functions provided by Valtio and they cover most use cases.
We then create a state
object with proxy
. In...