Immer
https://gyazo.com/9a0cc0a01c2d0adb5e56c6789c95418e
Immutableなオブジェクトを簡潔かつ堅牢に書くためのJavaScriptライブラリ.
オブジェクトのコピーに対して人間が修正を書き,Immerがその修正後のオブジェクトのコピーがImmutableに返ってくる.
バンドルサイズが非常に小さい.
gzipで3KB程度.
code:before.js
// Shallow Clone
const nextState = baseState.slice();
// Include another state value for update
nextState1 = {
...nextState1,
done: true,
};
// Updating by push.
// In this way, you will violate the immutability principles
nextState.push({ title: 'Tweet about it' });
code:after.js
import produce from 'immer';
const nextState = produce(baseState, draft => {
draft1.done = true;
draft.push({ title: 'Tweet about it' });
});
どんなに深いネストのフィールドでも素朴に変更可能
基本的に第二引数の関数は何も返さないが,オブジェクトを完全に変更したい場合などは変更後のオブジェクトを返して良い.
第一引数に関数を渡すことでカリー化ができる.
code:curried.js
const toggleTodo = (state, id) => {
return produce(state, draft => {
const todo = draft.find(t => t.id === id);
todo.done = !todo.done;
});
};
// 同等の処理が以下の書き方でできる
const toggleTodo = produce((draft, id) => {
const todo = draft.find(t => t.id === id);
todo.done = !todo.done;
});
バンドルサイズを小さくするため,一部の機能はopt-inとなっている.
ES5のサポート
MapやSetの利用
Proxyが利用できないInternet Explorerなどでは自動的にES5に対応した処理にフォールバックする.
React open source awardやJavaScript open source awardを受賞している.
#JavaScript