LoginSignup
1
1

More than 5 years have passed since last update.

bey

Last updated at Posted at 2018-05-31

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

気持ち

ミュータブルに書くとイミュータブルになるは、書く量が減って大変よろしいのであるが、パッと見たときにイミュータブルのシンタックスをしてないので心理的な抵抗がある。
慣れの問題かもしれないが、個人的には普通に{...}で新しいオブジェクトを返していくのが性にあってそう。

1
1
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
1
1