useSnapshot 返回的是只读快照,在快照上调用依赖 this 的方法会失败,建议用箭头函数;默认状态变更会批量合并再触发渲染,输入框等场景需传 { sync: true };useSnapshot 的 TypeScript 返回类型带 readonly 可能过严,需按 README 声明模块放宽
基于 Proxy 的极简状态管理库,让 React 和原生 JS 的状态读写像操作普通对象一样自然
基于 Proxy 的极简状态管理库,让 React 和原生 JS 中的可变状态自动触发更新,省去手写不可变数据的麻烦。
核心能力
- 用 proxy 包装状态对象,任意位置直接可变修改
- useSnapshot 按属性访问粒度触发重渲染
- subscribe 支持订阅整个状态或其中一部分
- 提供 proxySet、proxyMap、subscribeKey、watch 等工具
- 兼容 React 19 use 钩子,也可脱离 React 在 vanilla JS 使用
容易踩的坑
- v2.3.2最新正式版2026-05-01 · 2026-05-01 06:28 UTC
Workaround for React Native JS engine.
What's Changed
- fix(vanilla): remove Object.preventExtensions from createSnapshotDefault for Hermes compatibility by @manakuro in https://github.com/pmndrs/valtio/pull/1220
New Contributors
- @manakuro made their first contribution in https://github.com/pmndrs/valtio/pull/1220
Full Changelog: https://github.com/pmndrs/valtio/compare/v2.3.1...v2.3.2
- v2.3.12026-03-03 · 2026-03-03 05:52 UTC
查看更新说明
Reverted the useSnapshot change in v2.2.0 which seems to cause a problem in an edge case.
What's Changed
- fix: regression in #1176 by @dai-shi in https://github.com/pmndrs/valtio/pull/1206
New Contributors
- @pooya-badiee made their first contribution in https://github.com/pmndrs/valtio/pull/1193
- @ScreamZ made their first contribution in https://github.com/pmndrs/valtio/pull/1201
- @pavan-sh made their first contribution in https://github.com/pmndrs/valtio/pull/1202
Full Changelog: https://github.com/pmndrs/valtio/compare/v2.3.0...v2.3.1
- v2.3.02026-01-01 · 2026-01-01 09:41 UTC
查看更新说明
Improves performance by disabling an optional feature by default (now opt-in).
Migration Guide
To keep the previous behavior, you need to opt in the feature as follows:
import { unstable_enableOp } from 'valtio/vanilla'; unstable_enableOp(true);What's Changed
- feat(vanilla): make ops callback opt-in with unstable_enableOp by @dai-shi in https://github.com/pmndrs/valtio/pull/1189
- deprecate watch and derive by @dai-shi in https://github.com/pmndrs/valtio/pull/1190
New Contributors
- @joshua-tj made their first contribution in https://github.com/pmndrs/valtio/pull/1182
Full Changelog: https://github.com/pmndrs/valtio/compare/v2.2.0...v2.3.0
- v2.2.02025-11-03 · 2025-11-03 02:46 UTC
查看更新说明
This release contains some refactors. While it should work in most cases, we have a slight concern that it may behave a little differently in very edge cases. Feel free to report if you encounter such cases.
What's Changed
- refactor(utils): changes to proxySet for new typescript impl by @overthemike in https://github.com/pmndrs/valtio/pull/1175
- refactor(react): avoid eslint exception by @dai-shi in https://github.com/pmndrs/valtio/pull/1176
Full Changelog: https://github.com/pmndrs/valtio/compare/v2.1.8...v2.2.0
- v2.1.82025-09-25 · 2025-09-25 14:25 UTC
查看更新说明
This reverts one of the changes in v2.1.4.
⚠️ If you rely on the #1074 behavior of deepClone. This change is breaking. The migration path is to use
unstable_deepProxyinstead.What's Changed
- changed deepClone back to original and added deepProxy by @overthemike in https://github.com/pmndrs/valtio/pull/1169
New Contributors
- @01-binary made their first contribution in https://github.com/pmndrs/valtio/pull/1164
Full Changelog: https://github.com/pmndrs/valtio/compare/v2.1.7...v2.1.8
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
npm install valtio makes proxy-state simple
Wrap your state object
Valtio turns the object you pass it into a self-aware proxy.
import { proxy, useSnapshot } from 'valtio'
const state = proxy({ count: 0, text: 'hello' })
Mutate from anywhere
You can make changes to it in the same way you would to a normal js-object.
setInterval(() => {
++state.count
}, 1000)
React via useSnapshot
Create a local snapshot that catches changes. Rule of thumb: read from snapshots in render function, otherwise use the source. The component will only re-render when the parts of the state you access have changed, it is render-optimized.
// This will re-render on `state.count` change but not on `state.text` change
function Counter() {
const snap = useSnapshot(state)
return (
<div>
{snap.count}
<button onClick={() => ++state.count}>+1</button>
</div>
)
}
The snap variable returned by useSnapshot is a (deeply) read-only object.
Its type has readonly attribute, which may be too strict for some use cases.
To mitigate typing difficulties, you might want to loosen the type definition:
declare module 'valtio' {
function useSnapshot<T extends object>(p: T): T
}
See #327 for more information.
Internally, useSnapshot calls snapshot in valtio/vanilla,
and wraps the snapshot object with another proxy to detect property access.
This feature is based on proxy-compare.
Two kinds of proxies are used for different purposes:
proxy()fromvaltio/vanillais for mutation tracking or write tracking.createProxy()fromproxy-compareis for usage tracking or read tracking.
Valtio tries best to handle this behavior
but it's hard to understand without familiarity.
const state = proxy({
count: 0,
inc() {
++this.count
},
})
state.inc() // `this` points to `state` and it works fine
const snap = useSnapshot(state)
snap.inc() // `this` points to `snap` and it doesn't work because snapshot is frozen
To avoid this pitfall, the recommended pattern is not to use this and prefer arrow function.
const state = proxy({
count: 0,
inc: () => {
++state.count
},
})
If you are new to this, it's highly recommended to use eslint-plugin-valtio.
Subscribe from anywhere
You can access state outside of your components and subscribe to changes.
import { subscribe } from 'valtio'
// Subscribe to all state changes
const unsubscribe = subscribe(state, () =>
console.log('state has changed to', state),
)
// Unsubscribe by calling the result
unsubscribe()
You can also subscribe to a portion of state.
const state = proxy({ obj: { foo: 'bar' }, arr: ['hello'] })
subscribe(state.obj, () => console.log('state.obj has changed to', state.obj))
state.obj.foo = 'baz'
subscribe(state.arr, () => console.log('state.arr has changed to', state.arr))
state.arr.push('world')
To subscribe to a primitive value of state, consider subscribeKey in utils.
import { subscribeKey } from 'valtio/utils'
const state = proxy({ count: 0, text: 'hello' })
subscribeKey(state, 'count', (v) =>
console.log('state.count has changed to', v),
)
There is another util watch which might be convenient in some cases.
import { watch } from 'valtio/utils'
const state = proxy({ count: 0 })
const stop = watch((get) => {
console.log('state has changed to', get(state)) // auto-subscribe on use
})
Suspend your components
Valtio is compatible with React 19 use hook. This eliminates all the async back-and-forth, you can access your data directly while the parent is responsible for fallback state and error handling.
import { use } from 'react' // React 19
// import { use } from 'react18-use' // React 18
const state = proxy({ post: fetch(url).then((res) => res.json()) })
function Post() {
const snap = useSnapshot(state)
return <div>{use(snap.post).title}</div>
}
function App() {
return (
<Suspense fallback={<span>waiting...</span>}>
<Post />
</Suspense>
)
}
It still suffers from "de-opt", which prevents useTransition to work well. To mitigate it, there is a third-party library use-valtio.
Holding objects in state without tracking them
This may be useful if you have large, nested objects with accessors that you don't want to proxy. ref allows you to keep these objects inside the state model.
See #61 and #178 for more information.
When ref is passed an existing Valtio proxy, it returns the same proxy and globally marks it as untracked, including in later proxy composition. See the ref API documentation for details.
import { proxy, ref } from 'valtio'
const state = proxy({
count: 0,
dom: ref(document.body),
})
Update transiently (for often occurring state-changes)
You can read state in a component without causing re-render.
function Foo() {
const { count, text } = state
// ...
Or, you can have more control with subscribing in useEffect.
function Foo() {
const total = useRef(0)
useEffect(() => subscribe(state.arr, () => {
total.current = state.arr.reduce((p, c) => p + c)
}), [])
// ...
Update synchronously
By default, state mutations are batched before triggering re-render.
Sometimes, we want to disable the batching.
The known use case of this is <input> #270.
function TextBox() {
const snap = useSnapshot(state, { sync: true })
return (
<input value={snap.text} onChange={(e) => (state.text = e.target.value)} />
)
}
Dev tools
You can use Redux DevTools Extension for plain objects and arrays.
import { devtools } from 'valtio/utils'
const state = proxy({ count: 0, text: 'hello' })
const unsub = devtools(state, { name: 'state name', enabled: true })
Use it vanilla
Valtio is not tied to React, you can use it in vanilla-js.
import { proxy, subscribe, snapshot } from 'valtio/vanilla'
// import { ... } from 'valtio/vanilla/utils'
const state = proxy({ count: 0, text: 'hello' })
subscribe(state, () => {
console.log('state is mutated')
const obj = snapshot(state) // A snapshot is an immutable object
})
useProxy util
While the separation of proxy state and its snapshot is important, it's confusing for beginners. We have a convenient util to improve developer experience. useProxy returns shallow proxy state and its snapshot, meaning you can only mutate on root level.
import { useProxy } from 'valtio/utils'
const state = proxy({ count: 1 })
const Component = () => {
// useProxy returns a special proxy that can be used both in render and callbacks
// The special proxy has to be used directly in a function scope. You can't destructure it outside the scope.
const $state = useProxy(state)
return (
<div>
{$state.count}
<button onClick={() => ++$state.count}>+1</button>
</div>
)
}
Computed properties
You can define computed properties with object getters.
const state = proxy({
count: 1,
get doubled() {
return this.count * 2
},
})
Consider it as an advanced usage, because the behavior of this is sometimes confusing.
For more information, check out this guide.
proxySet util
This is to create a proxy which mimic the native Set behavior. The API is the same as Set API
import { proxySet } from 'valtio/utils'
const state = proxySet([1, 2, 3])
//can be used inside a proxy as well
//const state = proxy({
// count: 1,
// set: proxySet()
//})
state.add(4)
state.delete(1)
state.forEach((v) => console.log(v)) // 2,3,4
proxyMap util
This is to create a proxy which emulate the native Map behavior. The API is the same as Map API
import { proxyMap } from 'valtio/utils'
const state = proxyMap([
['key', 'value'],
['key2', 'value2'],
])
state.set('key', 'value')
state.delete('key')
state.get('key') // ---> value
state.forEach((value, key) => console.log(key, value)) // ---> "key", "value", "key2", "value2"
Compatibility
Valtio v2 works with React 18 and up.
It only depends on react and works with any
renderers such as react-dom, react-native, react-three-fiber, and so on.
Valtio works on Node.js, Next.js and other frameworks.
Valtio also works without React. See vanilla.
Plugins
Recipes
Valtio is unopinionated about best practices. The community is working on recipes.