use-history-state
Version:
`use-history-state` is replacement for `useState` that stores the state within the history state.
3 lines (2 loc) • 856 B
JavaScript
import{useEffect as t,useState as n,useCallback as o}from"react";var i=function(t,n){return void 0===n&&(n=window.history.state),n&&n[t]},e=function(t,n){return void 0===n&&(n=window.history.state),n&&t in n};export default function(r,a){if(!a)throw new Error("Must provide a key");var s=n(e(a)?i(a):r instanceof Function?r():r),u=s[0],w=s[1];t(function(){var t=function(t){var n=t.state,o=i(a,n);e(a,n)&&o!==u&&w(o)};return window.addEventListener("popstate",t),function(){window.removeEventListener("popstate",t)}},[a,u]);var c=o(function(t,n){var o,i,e;void 0===n&&(n=!1),e=t instanceof Function?t(u):t,w(e),n?window.history.replaceState(Object.assign({},window.history.state,((o={})[a]=e,o)),null):window.history.pushState(Object.assign({},window.history.state,((i={})[a]=e,i)),null)},[a,u]);return[u,c]}
//# sourceMappingURL=useHistoryState.es.js.map