14
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React #2Advent Calendar 2020

Day 15

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?