- Notifications
You must be signed in to change notification settings - Fork4
A 2-6x faster alternative to useState with spread operation.
License
mutativejs/use-mutative
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A hook to useMutative as a React hook to efficient update react state immutable with mutable way.
use-mutative is 2-6x faster thanuseState() with spread operation, more than 10x faster thanuseImmer().Read more about the performance comparison in Mutative.
Yarn
yarn add mutative use-mutative
NPM
npm install mutative use-mutative
Provide you can create immutable state easily with mutable way.
import{useMutative}from'use-mutative';exportfunctionApp(){const[todos,setTodos]=useMutative([{text:'todo'}]);return(<><buttononClick={()=>{// set todos with draft mutablesetTodos((draft)=>{draft.push({text:'todo 2'});});}}> click</button><buttononClick={()=>{// also can override value directlysetTodos([{text:'todo'},{text:'todo 2'}]);}}> click</button></>);}
Provide you can create immutable state easily with mutable way in reducer way.
For return values that do not contain any drafts, you can use
rawReturn()to wrap this return value to improve performance. It ensure that the return value is only returned explicitly.
import{rawReturn}from'mutative';import{useMutativeReducer}from'use-mutative';constinitialState={count:0,};functionreducer(draft:Draft<typeofinitialState>,action:{type:'reset'|'increment'|'decrement'}){switch(action.type){case'reset':returnrawReturn(initialState);case'increment':returnvoiddraft.count++;case'decrement':returnvoiddraft.count--;}}exportfunctionApp(){const[state,dispatch]=useMutativeReducer(reducer,initialState);return(<div> Count:{state.count}<br/><buttononClick={()=>dispatch({type:'increment'})}>Increment</button><buttononClick={()=>dispatch({type:'decrement'})}>Decrement</button><buttononClick={()=>dispatch({type:'reset'})}>Reset</button></div>);}
More detail aboutuse-mutative can be found inAPI docs
In some cases, you may want to get that patches from your update, we can pass{ enablePatches: true } options inuseMutative() oruseMutativeReducer(), that can provide you the ability to get that patches from pervious action.
const[state,updateState,patches,inversePatches]=useMutative(initState,{enablePatches:true,});const[state,dispatch,patches,inversePatches]=useMutativeReducer(reducer,initState,initializer,{enablePatches:true});
patches format will followhttps://jsonpatch.com/, but the"path" field be array structure.
use-mutative isMIT licensed.
About
A 2-6x faster alternative to useState with spread operation.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors5
Uh oh!
There was an error while loading.Please reload this page.