Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
React hook: useStorage
// A react hook to generalize the use of any class that implements the Storage interface.
// LocalStorage and SessionStorage are provided here but it is easy to extend to something like
// AsyncStorage for react native.
const useStorage = (key, initialValue, storage) => {
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
const item = storage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
return initialValue
useEffect(() => {
try {
// Update storage every time the value is changed
storage.setItem(key, JSON.stringify(storedValue))
} catch (e) {
}, [storedValue, storage, key])
return [storedValue, setStoredValue]
export const useLocalStorage = (key, initialValue) => {
return useStorage(key, initialValue, window.localStorage)
export const useSessionStorage = (key, initialValue) => {
return useStorage(key, initialValue, window.sessionStorage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment