💊 Valtio makes proxy-state simple Thursday, Nov 19, 2020

GitHUB SOURCE : https://github.com/pmndrs/valtio/

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!

Unauthorized reproduction of this site is prohibited, and offenders will be held accountable for their legal responsibilities.
Article Title: 💊 Valtio makes proxy-state simple
This article URL:💊 Valtio makes proxy-state simple

All Categories

Github Trending Repositories

Explore Github Trending Repositories. See what the GitHub community is most excited about today.

Copyright 2010 - 2020