use-persisted-state
Version:
A custom React Hook that provides a multi-instance, multi-tab/browser shared and persistent state.
2 lines (1 loc) • 1.29 kB
JavaScript
import{useRef as e,useState as n,useEffect as t,useCallback as o}from"react";import r from"@use-it/event-listener";var l={},a=function(e,n,t){return l[e]||(l[e]={callbacks:[],value:t}),l[e].callbacks.push(n),{deregister:function(){var t=l[e].callbacks,o=t.indexOf(n);o>-1&&t.splice(o,1)},emit:function(t){l[e].value!==t&&(l[e].value=t,l[e].callbacks.forEach(function(e){n!==e&&e(t)}))}}};export default function(l,u){if(void 0===u&&(u="undefined"!=typeof global&&global.localStorage?global.localStorage:"undefined"!=typeof globalThis&&globalThis.localStorage?globalThis.localStorage:"undefined"!=typeof window&&window.localStorage?window.localStorage:"undefined"!=typeof localStorage?localStorage:null),u){var i=function(e){return{get:function(n,t){var o=e.getItem(n);return null==o?"function"==typeof t?t():t:JSON.parse(o)},set:function(n,t){e.setItem(n,JSON.stringify(t))}}}(u);return function(u){return function(l,u,i){var c=i.get,f=i.set,g=e(null),s=n(function(){return c(u,l)}),d=s[0],p=s[1];r("storage",function(e){if(e.key===u){var n=JSON.parse(e.newValue);d!==n&&p(n)}}),t(function(){return g.current=a(u,p,l),function(){g.current.deregister()}},[l,u]);var v=o(function(e){var n="function"==typeof e?e(d):e;f(u,n),p(n),g.current.emit(e)},[d,f,u]);return[d,v]}(u,l,i)}}return n}