Created
September 24, 2023 16:08
-
-
Save osamajavaid/4cce79e6a74617eaa2bed03accdc05bd to your computer and use it in GitHub Desktop.
React useLocalStorage hook: Creates a stateful value that is persisted to localStorage, and a function to update it.
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
const useLocalStorage = (keyName, defaultValue) => { | |
const [storedValue, setStoredValue] = React.useState(() => { | |
try { | |
const value = window.localStorage.getItem(keyName); | |
if (value) { | |
return JSON.parse(value); | |
} else { | |
window.localStorage.setItem(keyName, JSON.stringify(defaultValue)); | |
return defaultValue; | |
} | |
} catch (err) { | |
return defaultValue; | |
} | |
}); | |
const setValue = newValue => { | |
try { | |
window.localStorage.setItem(keyName, JSON.stringify(newValue)); | |
} catch (err) {} | |
setStoredValue(newValue); | |
}; | |
return [storedValue, setValue]; | |
}; | |
const MyApp = () => { | |
const [name, setName] = useLocalStorage('name', 'John'); | |
return <input value={name} onChange={e => setName(e.target.value)} />; | |
}; | |
ReactDOM.createRoot(document.getElementById('root')).render( | |
<MyApp /> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment