Created
May 2, 2021 04:08
-
-
Save JayMGurav/3f6346be4294d75b1b3b0695b9fc5745 to your computer and use it in GitHub Desktop.
A custom hook to use localStorage
This file contains 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"; | |
const useLocalStorage = (initialState, key) => { | |
const [value, setValue] = useState(() => { | |
const keyValue = localStorage.getItem(key); | |
if(keyValue) return JSON.parse(keyValue)[value]; | |
return initialState; | |
}); | |
useEffect(() => { | |
localStorage.setItem(key, JSON.stringify({value}); | |
},[value]); | |
return [value, setValue]; | |
} | |
export default useLocalStorage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment