github

pmndrs / valtio

  • пятница, 20 ноября 2020 г. в 00:31:41
https://github.com/pmndrs/valtio

TypeScript
💊 Valtio makes proxy-state simple



Alt. Description

Valtio

npm i valtio makes proxy-state simple

Wrap your state object

import { proxy, useProxy } from 'valtio'

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

Mutate from anywhere

setInterval(() => {
  ++state.count
}, 1000)

React via useProxy

function Counter() {
  const snapshot = useProxy(state)
  // Rule of thumb: read from snapshots, mutate the source
  // The component renders when the snapshot-reads change
  return (
    <div>
      {snapshot.count}
      <button onClick={() => ++state.count}>+1</button>
    </div>
  )
}

Subscribe from anywhere

import { subscribe } from 'valtio'

// Suscribe to all state changes
const unsubscribe = subscribe(state, () => console.log(`state has changed to ${state}`))
// Unsubscribe by calling the result
unsubscribe()
// Subscribe to a portion of state
subscribe(state.foo, () => console.log(`state.foo has changed to ${state.foo}`))

And that's it!