-
Notifications
You must be signed in to change notification settings - Fork 1
React Persist Context to LocalStorage
Jason Lewis edited this page Mar 31, 2022
·
2 revisions
- Add a couple methods to your Context file (or anywhere and import them)
function setLocalStorage(key, value) { try { function setLocalStorage(key, value) { try { window.localStorage.setItem(key, JSON.stringify(value)); } catch (e) { // catch possible errors: // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API } } function getLocalStorage(key, initialValue) { try { const value = window.localStorage.getItem(key); return value ? JSON.parse(value) : initialValue; } catch (e) { // if error, return initial value return initialValue; } } window.localStorage.setItem(key, JSON.stringify(value)); } catch (e) { // catch possible errors: // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API } }
- Initialize your state by reading from LocalStorage. E.g.
const [userId, setUserId] = useState(() => getLocalStorage("userId", ""));
- Update LocalStorage when state changes. E.g.
useEffect(() => { setLocalStorage("userId", userId); }, [userId]);