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.56 kB
JavaScript
;var e=require("mutative"),r=require("react");exports.useMutative=function(t,c){const u=r.useRef({patches:[],inversePatches:[]}),n=r.useRef(0),s=r.useRef(0);let a=n.current;r.useEffect((()=>{n.current=a,s.current=a})),a+=1,s.current+=1;const[p,o]=r.useState((()=>"function"==typeof t?t():t)),h=r.useCallback((r=>{o((t=>{const a="function"==typeof r?r:()=>r,p=e.create(t,a,c);return(null==c?void 0:c.enablePatches)?(s.current!==n.current&&s.current!==n.current+1||(Array.prototype.push.apply(u.current.patches,p[1]),Array.prototype.unshift.apply(u.current.inversePatches,p[2])),p[0]):p}))}),[]);return r.useEffect((()=>{(null==c?void 0:c.enablePatches)&&(u.current.patches=[],u.current.inversePatches=[])})),(null==c?void 0:c.enablePatches)?[p,h,u.current.patches,u.current.inversePatches]:[p,h]},exports.useMutativeReducer=function(t,c,u,n){const s=r.useRef({patches:[],inversePatches:[]}),a=r.useRef(0),p=r.useRef(0);let o=a.current;r.useEffect((()=>{a.current=o,p.current=o})),o+=1,p.current+=1;const h=r.useMemo((()=>(r,c)=>{const u=e.create(r,(e=>t(e,c)),n);return(null==n?void 0:n.enablePatches)?(p.current!==a.current&&p.current!==a.current+1||(Array.prototype.push.apply(s.current.patches,u[1]),Array.prototype.unshift.apply(s.current.inversePatches,u[2])),u[0]):u}),[t]),i=r.useReducer(h,c,u);return r.useEffect((()=>{(null==n?void 0:n.enablePatches)&&(s.current.patches=[],s.current.inversePatches=[])})),(null==n?void 0:n.enablePatches)?[i[0],i[1],s.current.patches,s.current.inversePatches]:i};
//# sourceMappingURL=index.cjs.js.map