valtio README

The project's README from github.com/pmndrs/valtio. As one markdown file: README.md.

valtio

npm install valtio makes proxy-state simple

Build Status Build Size Version Downloads Discord Shield

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>
  )
}
Note for TypeScript users: Return type of useSnapshot can be too strict.

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.

Note: useSnapshot returns a new proxy for render optimization.

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() from valtio/vanilla is for mutation tracking or write tracking.
  • createProxy() from proxy-compare is for usage tracking or read tracking.
Use of this is for expert users.

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 })
Manipulating state with Redux DevTools The screenshot below shows how to use Redux DevTools to manipulate state. First select the object from the instances drop down. Then type in a JSON object to dispatch. Then click "Dispatch". Notice how it changes the state.
image

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.

valtio (pmndrs/valtio)

Searching Database…

10.2K ·GitHub
这是什么?Valtio 是一个小型的状态管理库:你把任意 JS 对象包起来,它就会变成一个有感知能力的代理(proxy),当组件读取的数据发生变化时,React 组件会自动重新渲染。它也可以脱离 React 单独使用。
它是一个只能配合 React 用的库,还是我在 React 之外也能用?它是一个普通的库,不是框架。它通过 useSnapshot 钩子为 React 而设计,但并不绑定 React——它的代理状态核心也能在原生 JS 应用中运行。
我怎么把它加到我的项目里?运行 npm install valtio,用 proxy() 包住你的状态对象,然后在组件里用 useSnapshot(state) 读取它。直接修改被包裹的对象就会触发更新。
它对 React 版本有要求吗?还会引入其他依赖吗?Valtio v2 需要 React 18 或更新版本,并且只依赖 react。它可以配合任何渲染器使用——react-dom、react-native、react-three-fiber——此外还支持 Node.js 和 Next.js。
在使用之前,有什么坑是我需要知道的?useSnapshot 返回一个深度只读的对象,它的 TypeScript 类型有时会过于严格;而且“写代理、读快照”的分工模式也很容易用错。推荐的防护措施是使用 eslint-plugin-valtio 这个 lint 工具。
我可以在 React 组件之外响应状态变化吗?可以。subscribe 让你在任何地方监听变化,包括只监听状态的一部分。对于原始值还有 subscribeKey 这个工具函数,更复杂的情况则可以用 watch 辅助函数。
如果我的状态需要用到 Map 或 Set 怎么办?有 proxyMap 和 proxySet 这两个工具函数,它们会创建模仿原生 Map 和 Set 行为的代理,API 与内置的完全一样。
它对异步数据获取有帮助吗?它与 React 19 的 use 钩子兼容,所以组件可以在数据加载时挂起,并直接读取结果,而由父组件处理加载占位和错误状态。useTransition 存在一个已知的性能回退问题,可以用第三方库 use-valtio 来缓解。
我可以把某些对象放进状态里但不让它被追踪吗?可以——用 ref() 包裹它们,就能把它们存进状态模型而不做代理,这对于带有访问器的大型嵌套对象很有用。把一个已经存在的 Valtio 代理传给 ref,会让它在全局范围内不再被追踪。
Creator
pmndrs
Size
6 MB
Stars
10.2K
Age
5y
Commits · 90 Days