UNPKG

react-use

Version:
38 lines (37 loc) 1.38 kB
import { useEffect, useState } from 'react'; import { isClient } from './util'; var useLocalStorage = function (key, initialValue, raw) { if (!isClient) { return [initialValue, function () { }]; } var _a = useState(function () { try { var localStorageValue = localStorage.getItem(key); if (typeof localStorageValue !== 'string') { localStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue)); return initialValue; } else { return raw ? localStorageValue : JSON.parse(localStorageValue || 'null'); } } catch (_a) { // If user is in private mode or has storage restriction // localStorage can throw. JSON.parse and JSON.stringify // can throw, too. return initialValue; } }), state = _a[0], setState = _a[1]; useEffect(function () { try { var serializedState = raw ? String(state) : JSON.stringify(state); localStorage.setItem(key, serializedState); } catch (_a) { // If user is in private mode or has storage restriction // localStorage can throw. Also JSON.stringify can throw. } }, [state]); return [state, setState]; }; export default useLocalStorage;