use-mutative
Version:
A hook to use Mutative as a React hook to efficient update react state immutable with mutable way
3 lines (2 loc) • 1.5 kB
JavaScript
import{create as e}from"mutative";import{useRef as r,useEffect as t,useState as n,useCallback as c,useMemo as u,useReducer as s}from"react";function a(u,s){const a=r({patches:[],inversePatches:[]}),o=r(0),p=r(0);let h=o.current;t((()=>{o.current=h,p.current=h})),h+=1,p.current+=1;const[l,i]=n((()=>"function"==typeof u?u():u)),v=c((r=>{i((t=>{const n=e(t,"function"==typeof r?r:()=>r,s);return(null==s?void 0:s.enablePatches)?(p.current!==o.current&&p.current!==o.current+1||(Array.prototype.push.apply(a.current.patches,n[1]),Array.prototype.unshift.apply(a.current.inversePatches,n[2])),n[0]):n}))}),[]);return t((()=>{(null==s?void 0:s.enablePatches)&&(a.current.patches=[],a.current.inversePatches=[])})),(null==s?void 0:s.enablePatches)?[l,v,a.current.patches,a.current.inversePatches]:[l,v]}function o(n,c,a,o){const p=r({patches:[],inversePatches:[]}),h=r(0),l=r(0);let i=h.current;t((()=>{h.current=i,l.current=i})),i+=1,l.current+=1;const v=u((()=>(r,t)=>{const c=e(r,(e=>n(e,t)),o);return(null==o?void 0:o.enablePatches)?(l.current!==h.current&&l.current!==h.current+1||(Array.prototype.push.apply(p.current.patches,c[1]),Array.prototype.unshift.apply(p.current.inversePatches,c[2])),c[0]):c}),[n]),y=s(v,c,a);return t((()=>{(null==o?void 0:o.enablePatches)&&(p.current.patches=[],p.current.inversePatches=[])})),(null==o?void 0:o.enablePatches)?[y[0],y[1],p.current.patches,p.current.inversePatches]:y}export{a as useMutative,o as useMutativeReducer};
//# sourceMappingURL=index.esm.js.map