A hook for creating the immutable state with mutations on React, it's based on immer.
- Update state by mutating
- Snapshot
- Time traveling
- Installation
yarn add use-immutable
- Example: Demo
import React from 'react';
import { useImmutable } from 'use-immutable';
const TodoList = () => {
const todo = useImmutable({
text: '',
list: [],
});
const updateText = (e) =>
todo.set(() => {
todo.state.text = e.target.value;
});
const addTodo = () =>
todo.set(() => {
todo.state.list.push(todo.state.text);
todo.state.text = '';
});
return (
<div>
<input value={todo.state.text} onChange={updateText} />
<button onClick={addTodo}>Add</button>
<ul>
{todo.state.list.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
Get the current component status.
Take a snapshot of the current state
Update the state from the snapshot
Clear the snapshot
Get the snapshot length
Index of the current state in the snapshot
Set a new state value