Creates a stateful value that is persisted to localStorage
, and a function to update it.
useState()
hook with a function to initialize its value lazily.try...catch
block and Storage.getItem()
to try and get the value from Window.localStorage
. If no value is found, use Storage.setItem()
to store the defaultValue
and use it as the initial state. If an error occurs, use defaultValue
as the initial state.Storage.setItem()
to store it.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.render(<MyApp />, document.getElementById('root'));
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Hooks
Returns a stateful value, persisted in localStorage
, and a function to update it.
React, Hooks
Creates a stateful value that is persisted to sessionStorage
, and a function to update it.
React, Hooks
Creates a stateful value, and a function to update it by merging the new state provided.