Valtio

Valtio makes proxy-state simple for React and Vanilla

README

valtio

npm i 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.

  1. ```jsx
  2. import { proxy, useSnapshot } from 'valtio'

  3. const state = proxy({ count: 0, text: 'hello' })
  4. ```

Mutate from anywhere


You can make changes to it in the same way you would to a normal js-object.

  1. ```jsx
  2. setInterval(() => {
  3.   ++state.count
  4. }, 1000)
  5. ```

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.

  1. ```jsx
  2. // This will re-render on `state.count` change but not on `state.text` change
  3. function Counter() {
  4.   const snap = useSnapshot(state)
  5.   return (
  6.     <div>
  7.       {snap.count}
  8.       <button onClick={() => ++state.count}>+1</button>
  9.     </div>
  10.   )
  11. }
  12. ```

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:

  1. ```ts
  2. declare module 'valtio' {
  3.   function useSnapshot<T extends object>(p: T): T
  4. }
  5. ```

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.

  1. ```js
  2. const state = proxy({
  3.   count: 0,
  4.   inc() {
  5.     ++this.count
  6.   },
  7. })
  8. state.inc() // `this` points to `state` and it works fine
  9. const snap = useSnapshot(state)
  10. snap.inc() // `this` points to `snap` and it doesn't work because snapshot is frozen
  11. ```

To avoid this pitfall, the recommended pattern is not to use this and prefer arrow function.

  1. ```js
  2. const state = proxy({
  3.   count: 0,
  4.   inc: () => {
  5.     ++state.count
  6.   },
  7. })
  8. ```


If you are new to this, it's highly recommended to use

Subscribe from anywhere


You can access state outside of your components and subscribe to changes.

  1. ```jsx
  2. import { subscribe } from 'valtio'

  3. // Subscribe to all state changes
  4. const unsubscribe = subscribe(state, () =>
  5.   console.log('state has changed to', state)
  6. )
  7. // Unsubscribe by calling the result
  8. unsubscribe()
  9. ```

You can also subscribe to a portion of state.

  1. ```jsx
  2. const state = proxy({ obj: { foo: 'bar' }, arr: ['hello'] })

  3. subscribe(state.obj, () => console.log('state.obj has changed to', state.obj))
  4. state.obj.foo = 'baz'

  5. subscribe(state.arr, () => console.log('state.arr has changed to', state.arr))
  6. state.arr.push('world')
  7. ```

To subscribe to a primitive value of state, consider subscribeKey in utils.

  1. ```jsx
  2. import { subscribeKey } from 'valtio/utils'

  3. const state = proxy({ count: 0, text: 'hello' })
  4. subscribeKey(state, 'count', (v) =>
  5.   console.log('state.count has changed to', v)
  6. )
  7. ```

There is another util watch which might be convenient in some cases.

  1. ```jsx
  2. import { watch } from 'valtio/utils'

  3. const state = proxy({ count: 0 })
  4. const stop = watch((get) => {
  5.   console.log('state has changed to', get(state)) // auto-subscribe on use
  6. })
  7. ```

Suspend your components


Valtio supports React-suspense and will throw promises that you access within a components render function. 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.

  1. ```jsx
  2. const state = proxy({ post: fetch(url).then((res) => res.json()) })

  3. function Post() {
  4.   const snap = useSnapshot(state)
  5.   return <div>{snap.post.title}</div>
  6. }

  7. function App() {
  8.   return (
  9.     <Suspense fallback={<span>waiting...</span>}>
  10.       <Post />
  11.     </Suspense>
  12.   )
  13. }
  14. ```

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.

  1. ```js
  2. import { proxy, ref } from 'valtio'

  3. const state = proxy({
  4.   count: 0,
  5.   dom: ref(document.body),
  6. })
  7. ```

Update transiently (for often occurring state-changes)


You can read state in a component without causing re-render.

  1. ```jsx
  2. function Foo() {
  3.   const { count, text } = state
  4.   // ...
  5. ```

Or, you can have more control with subscribing in useEffect.

  1. ```jsx
  2. function Foo() {
  3.   const total = useRef(0)
  4.   useEffect(() => subscribe(state.arr, () => {
  5.     total.current = state.arr.reduce((p, c) => p + c)
  6.   }), [])
  7.   // ...
  8. ```

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 `` [#270](https://github.com/pmndrs/valtio/issues/270).

  1. ```jsx
  2. function TextBox() {
  3.   const snap = useSnapshot(state, { sync: true })
  4.   return (
  5.     <input value={snap.text} onChange={(e) => (state.text = e.target.value)} />
  6.   )
  7. }
  8. ```

Dev tools


You can use Redux DevTools Extension for plain objects and arrays.

  1. ```jsx
  2. import { devtools } from 'valtio/utils'

  3. const state = proxy({ count: 0, text: 'hello' })
  4. const unsub = devtools(state, { name: 'state name', enabled: true })
  5. ```

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.

  1. ```jsx
  2. import { proxy, subscribe, snapshot } from 'valtio/vanilla'

  3. const state = proxy({ count: 0, text: 'hello' })

  4. subscribe(state, () => {
  5.   console.log('state is mutated')
  6.   const obj = snapshot(state) // A snapshot is an immutable object
  7. })
  8. ```

useProxy macro


We have a convenient macro with

  1. ```js
  2. import { useProxy } from 'valtio/macro'

  3. const Component = () => {
  4.   useProxy(state)
  5.   return (
  6.     <div>
  7.       {state.count}
  8.       <button onClick={() => ++state.count}>+1</button>
  9.     </div>
  10.   )
  11. }

  12. // the code above becomes the code below.

  13. import { useSnapshot } from 'valtio'

  14. const Component = () => {
  15.   const snap = useSnapshot(state)
  16.   return (
  17.     <div>
  18.       {snap.count}
  19.       <button onClick={() => ++state.count}>+1</button>
  20.     </div>
  21.   )
  22. }
  23. ```

vite

  1. ```
  2. npm i --save-dev aslemammad-vite-plugin-macro babel-plugin-macros
  3. ```

And in your vite.config.js

  1. ```js
  2. import { defineConfig } from 'vite'
  3. import macro from 'valtio/macro/vite'

  4. export default defineConfig({
  5.   plugins: [macro],
  6. })
  7. ```

derive util


You can subscribe to some proxies and create a derived proxy.

  1. ```js
  2. import { derive } from 'valtio/utils'

  3. // create a base proxy
  4. const state = proxy({
  5.   count: 1,
  6. })

  7. // create a derived proxy
  8. const derived = derive({
  9.   doubled: (get) => get(state).count * 2,
  10. })

  11. // alternatively, attach derived properties to an existing proxy
  12. derive(
  13.   {
  14.     tripled: (get) => get(state).count * 3,
  15.   },
  16.   {
  17.     proxy: state,
  18.   }
  19. )
  20. ```

proxyWithComputed util


You can define own computed properties within a proxy.
By combining with a memoization library such as
optimizing function calls is possible.

Be careful not to overuse proxy-memoize
because proxy-memoize and useSnapshot do similar optimization
and double optimization may lead to less performance.

  1. ```js
  2. import memoize from 'proxy-memoize'
  3. import { proxyWithComputed } from 'valtio/utils'

  4. const state = proxyWithComputed(
  5.   {
  6.     count: 1,
  7.   },
  8.   {
  9.     doubled: memoize((snap) => snap.count * 2),
  10.   }
  11. )

  12. // Computed values accept custom setters too:
  13. const state2 = proxyWithComputed(
  14.   {
  15.     firstName: 'Alec',
  16.     lastName: 'Baldwin',
  17.   },
  18.   {
  19.     fullName: {
  20.       get: memoize((snap) => snap.firstName + ' ' + snap.lastName),
  21.       set: (state, newValue) => {
  22.         ;[state.firstName, state.lastName] = newValue.split(' ')
  23.       },
  24.     },
  25.   }
  26. )

  27. // if you want a computed value to derive from another computed, you must declare the dependency first:
  28. const state = proxyWithComputed(
  29.   {
  30.     count: 1,
  31.   },
  32.   {
  33.     doubled: memoize((snap) => snap.count * 2),
  34.     quadrupled: memoize((snap) => snap.doubled * 2),
  35.   }
  36. )
  37. ```

The last use case fails to infer types in TypeScript

proxyWithHistory util


This is a utility function to create a proxy with snapshot history.

  1. ```js
  2. import { proxyWithHistory } from 'valtio/utils'

  3. const state = proxyWithHistory({ count: 0 })
  4. console.log(state.value) // ---> { count: 0 }
  5. state.value.count += 1
  6. console.log(state.value) // ---> { count: 1 }
  7. state.undo()
  8. console.log(state.value) // ---> { count: 0 }
  9. state.redo()
  10. console.log(state.value) // ---> { count: 1 }
  11. ```

proxySet util


This is to create a proxy which mimic the native Set behavior. The API is the same as Set API

  1. ```js
  2. import { proxySet } from 'valtio/utils'

  3. const state = proxySet([1, 2, 3])
  4. //can be used inside a proxy as well
  5. //const state = proxy({
  6. //    count: 1,
  7. //    set: proxySet()
  8. //})

  9. state.add(4)
  10. state.delete(1)
  11. state.forEach((v) => console.log(v)) // 2,3,4
  12. ```

proxyMap util


This is to create a proxy which emulate the native Map behavior. The API is the same as Map API

  1. ```js
  2. import { proxyMap } from 'valtio/utils'

  3. const state = proxyMap([
  4.   ['key', 'value'],
  5.   ['key2', 'value2'],
  6. ])
  7. state.set('key', 'value')
  8. state.delete('key')
  9. state.get('key') // ---> value
  10. state.forEach((value, key) => console.log(key, value)) // ---> "key", "value", "key2", "value2"
  11. ```

Compatibility


Valtio works with React with hooks support (>=16.8).
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 on wiki pages.