UNPKG

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.81 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("mutative"),require("react")):"function"==typeof define&&define.amd?define(["exports","mutative","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).UseMutative={},e.Mutative,e.React)}(this,(function(e,t,r){"use strict";e.useMutative=function(e,n){const u=r.useRef({patches:[],inversePatches:[]}),c=r.useRef(0),s=r.useRef(0);let a=c.current;r.useEffect((()=>{c.current=a,s.current=a})),a+=1,s.current+=1;const[o,i]=r.useState((()=>"function"==typeof e?e():e)),f=r.useCallback((e=>{i((r=>{const a="function"==typeof e?e:()=>e,o=t.create(r,a,n);return(null==n?void 0:n.enablePatches)?(s.current!==c.current&&s.current!==c.current+1||(Array.prototype.push.apply(u.current.patches,o[1]),Array.prototype.unshift.apply(u.current.inversePatches,o[2])),o[0]):o}))}),[]);return r.useEffect((()=>{(null==n?void 0:n.enablePatches)&&(u.current.patches=[],u.current.inversePatches=[])})),(null==n?void 0:n.enablePatches)?[o,f,u.current.patches,u.current.inversePatches]:[o,f]},e.useMutativeReducer=function(e,n,u,c){const s=r.useRef({patches:[],inversePatches:[]}),a=r.useRef(0),o=r.useRef(0);let i=a.current;r.useEffect((()=>{a.current=i,o.current=i})),i+=1,o.current+=1;const f=r.useMemo((()=>(r,n)=>{const u=t.create(r,(t=>e(t,n)),c);return(null==c?void 0:c.enablePatches)?(o.current!==a.current&&o.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}),[e]),p=r.useReducer(f,n,u);return r.useEffect((()=>{(null==c?void 0:c.enablePatches)&&(s.current.patches=[],s.current.inversePatches=[])})),(null==c?void 0:c.enablePatches)?[p[0],p[1],s.current.patches,s.current.inversePatches]:p}})); //# sourceMappingURL=index.umd.js.map