Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useLocalStorage React Hook
import { useState, useEffect } from 'react';
export const useLocalStorage = (storageKey, initialValue) => {
const [storageVal, setStorageVal] = useState(getFromLocalStorage(storageKey));
useEffect(() => {
setToLocalStorage(storageKey, storageVal);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [storageVal]);
return [storageVal, setStorageVal];
};
const getFromLocalStorage = key => {
const value = localStorage.getItem(key);
try {
return JSON.parse(value); //incase of json is stored;
} catch (error) {
//silently return the value;
return value;
}
};
const setToLocalStorage = (key, value) => {
if (typeof value === 'object' && value) {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment