LoginSignup
14
4

More than 3 years have passed since last update.

Valtioで超絶簡単React状態管理

Last updated at Posted at 2020-12-14

valtio (1).png

ステートオブジェクトを包む

import { proxy, useProxy } from 'valtio'

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

どこからでも変更できる

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

useProxyでReactへ

function Counter() {
  const snapshot = useProxy(state)
  // 読み込む場合はsnapshot、いじる場合はstate
  // snapshotの読み込み部分が変化したら再描画される
  return (
    <div>
      {snapshot.count}
      <button onClick={() => ++state.count}>+1</button>
    </div>
  )
}
14
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
4