use-immutable
v0.3.0
Published
A hook for creating the immutable state with mutations on React
Downloads
108
Readme
use-immutable
A hook for creating the immutable state with mutations on React, it's based on immer.
Features
- Update state by mutating
- Snapshot
- Time traveling
Usage
- 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>
);
};
APIs
instance.state
Get the current component status.
instance.snapshot()
Take a snapshot of the current state
instance.pop()
Update the state from the snapshot
instance.clear()
Clear the snapshot
instance.length
Get the snapshot length
instance.index
Index of the current state in the snapshot
instance.set()
Set a new state value