Skip to main content
Module

x/valtio/docs/basic/useSnapshot.mdx

πŸ’Š Valtio makes proxy-state simple for React and Vanilla
Go to Latest
File
---title: 'useSnapshot'section: 'Basic'description: 'Create a local snapshot taht catches changes.'---
# useSnapshot
Create a local snapshot that catches changes. This hook actually returns a wrapped snapshot in a proxy forrender optimization instead of a plain object compared to <a href="/docs/advanced/snapshot">`snapshot()`</a>.
#### Rule of thumb: read from snapshots, mutate the source.
The component will only re-render when the parts of the state you access have changed; it is render-optimized.
```jsxfunction Counter() { const snap = useSnapshot(state) return ( <div> {snap.count} <button onClick={() => ++state.count}>+1</button> </div> )}```
#### Read only what you need
Every object inside your proxy also becomes a proxy (if you don't use <a href="/docs/advanced/ref">`ref()`</a>). So you can also use them to createa local snapshot.
```jsxfunction ProfileName() { const snap = useSnapshot(state.profile) return <div>{snap.name}</div>}```
#### Gotchas
Beware of replacing the child proxy with something else, breaking your snapshot. You can seehere what happens with the original proxy when you replace the child proxy.
```jsconsole.log(state){ profile: { name: 'valtio' }}childState = state.profileconsole.log(childState){ name: 'valtio'}state.profile.name = 'react'console.log(childState){ name: 'react'}state.profile = { name: 'new name' }console.log(childState){ name: 'react'}console.log(state){ profile: { name: 'new name' }}```
`useSnapshot()` depends on the original reference of the child proxy so if you replace it with a new one, the componentthat is subscribed to the old proxy won't receive new updates because it is still subscribed to the old one.
In this case, we recommend one of the approaches below. In neither example do you need to worry about re-renders because it is render-optimized.
```jsxconst snap = useSnapshot(state)
return <div>{snap.profile.name}</div>```
```jsxconst { profile } = useSnapshot(state)
return <div>{profile.name}</div>```
## Codesandbox demo
https://codesandbox.io/s/ping-pong-with-valtio-wb25s?file=/src/App.js