Simple immutable state for React using Immer
immerを使ったReactコンポーネント。
サンプルと見ると、update
でミュータブルな操作をしているが、実際はimmerによってイミュータブルに変更されている。
あとは、普通にrender propで変更があれば新しくstateが流れる。
bey
の実装自体もすぐに読めるが、this.setState({})
でライフサイクルを回してる部分は面白い。
以下、サンプル
import React from 'react'
import { render } from 'react-dom'
import { state, update, Subscribe } from 'bey'
const counter = state({ count: 0 })
function increment() {
update(counter, state => {
state.count++
})
}
function decrement() {
update(counter, state => {
state.count--
})
}
function Counter() {
return (
<Subscribe to={counter} on={state => state.count}>
{count => (
<div>
<button onClick={decrement}>-</button>
<span>{count}</span>
<button onClick={increment}>+</button>
</div>
)}
</Subscribe>
)
}
render(<Counter />, document.querySelector('#app'))
雑に試すのにparcel
がオススメなので絶対使った方がいいです。
<div id="app"></div>
<script src="./src/index.js"></script>
$ parcel index.html
気持ち
ミュータブルに書くとイミュータブルになるは、書く量が減って大変よろしいのであるが、パッと見たときにイミュータブルのシンタックスをしてないので心理的な抵抗がある。
慣れの問題かもしれないが、個人的には普通に{...}
で新しいオブジェクトを返していくのが性にあってそう。