Created
June 27, 2019 07:29
-
-
Save ritwickdey/ea8ae4737e0a7013e900aa5269191305 to your computer and use it in GitHub Desktop.
useLocalStorage React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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