Created
January 15, 2024 13:48
-
-
Save brunobertolini/c0b46130f25d92df98ddc39b7d57c6c5 to your computer and use it in GitHub Desktop.
A react useState with localStorage persistence
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 { useEffect, useState } from 'react' | |
export const useStorage = (key, defaultValue) => { | |
const [value, setValue] = useState(() => { | |
const storedValue = typeof window !== 'undefined' && window?.localStorage.getItem(key) | |
return (storedValue && JSON.parse(storedValue)[key]) || defaultValue | |
}) | |
useEffect(() => { | |
const valueToStore = { [key]: value } | |
console.log(valueToStore) | |
typeof window !== 'undefined' && window?.localStorage?.setItem(key, JSON.stringify(valueToStore)) | |
}, [value, window]) | |
return [value, setValue] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment