Skip to content

Instantly share code, notes, and snippets.

@opensourcekam
Last active October 1, 2019 22:26
Show Gist options
  • Save opensourcekam/3de4d925b9a96285f509ce799178118b to your computer and use it in GitHub Desktop.
Save opensourcekam/3de4d925b9a96285f509ce799178118b to your computer and use it in GitHub Desktop.
use state with persistent storage
import { useState, useEffect } from 'react';
export const useStateLocalStorage = (localStorageKey, initialState = "") => {
const init = localStorage.getItem(localStorageKey) || initialState;
const [value, setValue] = useState(init);
useEffect(() => {
localStorage.setItem(localStorageKey, value);
}, [value]);
return [value, setValue];
};
import { useState, useEffect } from 'react';
export const useStateSessionStorage = (localStorageKey, initialState = "") => {
const init = sessionStorage.getItem(localStorageKey) || initialState;
const [value, setValue] = useState(init);
useEffect(() => {
sessionStorage.setItem(localStorageKey, value);
}, [value]);
return [value, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment