Last active
June 21, 2022 17:59
-
-
Save robertocinetto/3486c244645db155e9afdcb97edb52a4 to your computer and use it in GitHub Desktop.
useLocalStorage.js - React custom hook that inherits useState functionality and store value on browser local storage. Needs a key to be passed together with the value.
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"; | |
// get already saved value from local storage | |
function getSavedValue(key, initialValue) { | |
//retrieve value from local storage | |
const savedValue = JSON.parse(localStorage.getItem(key)); | |
//check if a value for that key already exists | |
if (savedValue) return savedValue; | |
//since useState can receive a function with check for it in the initial value | |
if (initialValue instanceof Function) return initialValue(); | |
//otherwise returns the initial value | |
return initialValue; | |
} | |
export default function useLocalStorage(key, initialValue) { | |
//first thing first is to save the key:value in the state using useState | |
const [value, setValue] = useState(() => { | |
return getSavedValue(key, initialValue); | |
}); | |
//every time 'value' changes save value to localstorage | |
useEffect(() => { | |
localStorage.setItem(key, JSON.stringify(value)); | |
}, [value]); | |
return [value, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment