기본 소개

Proxy 기반 React 상태관리 도구

Untitled

제공 API

proxy

import { proxy } from 'valtio'

const state1 = proxy({ count: 0, text: 'hello' })
const state2 = proxy(new User('Timo', 'Kivinen'))

snapshot

const state = proxy({ a: { aa: 1 }, b: { bb: 2 } })
const snap1 = snapshot(state)
const newSnap = snapshot(state.a);

console.log(snap1) // ---> { a: { aa: 1 }, b: { bb: 2 } }
++state.a.aa
const snap2 = snapshot(state)
console.log(snap2) // ---> { a: { aa: 2 }, b: { bb: 2 } }
snap1.b === snap2.b // this is `true`, it doesn't create a new snapshot because no properties are changed.

useSnapshot

function Counter() {
  const snap = useCard();

  return (
    <div>
      {snap.count}
      <button
        onClick={() => {
          // also read from the state proxy in callbacks
          if (state.count < 10) {
            ++state.count
          }
        }
      >
        +1
      </button>
    </div>
  )
}

useProxy

function Counter() {
  const store = useProxy(state);

  return (
    <div>
      {store.count}
      <button
        onClick={() => {
          // also read from the state proxy in callbacks
          if (store.count < 10) {
            ++store.count
          }
        }
      >
        +1
      </button>
    </div>
  )
}

subscribe