Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Created June 27, 2019 07:29
Show Gist options
  • Save ritwickdey/ea8ae4737e0a7013e900aa5269191305 to your computer and use it in GitHub Desktop.
Save ritwickdey/ea8ae4737e0a7013e900aa5269191305 to your computer and use it in GitHub Desktop.
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