JAVASCRIPT
Persisting State with useLocalStorage
Create a custom React hook `useLocalStorage` to effortlessly synchronize your component's state with the browser's Local Storage, ensuring data persistence across sessions.
import { useState, useEffect } from 'react';
const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(`Error writing to localStorage key “${key}”:`, error);
}
};
useEffect(() => {
// This effect ensures that if initialValue changes, we update storedValue
// only if the item doesn't exist in localStorage yet.
// If it exists, we stick to what's in localStorage.
try {
const item = window.localStorage.getItem(key);
if (!item) {
window.localStorage.setItem(key, JSON.stringify(initialValue));
setStoredValue(initialValue);
}
} catch (error) {
console.warn(`Error synchronizing initialValue for localStorage key “${key}”:`, error);
}
}, [key, initialValue]);
return [storedValue, setValue];
};
export default useLocalStorage;
// Example Usage:
// function UserNameInput() {
// const [name, setName] = useLocalStorage('userName', 'Guest');
//
// return (
// <div>
// <input
// type="text"
// value={name}
// onChange={(e) => setName(e.target.value)}
// placeholder="Enter your name"
// />
// <p>Hello, {name}!</p>
// </div>
// );
// }
How it works: The `useLocalStorage` hook provides a convenient way to manage state that persists across browser sessions. It initializes state by attempting to load from `localStorage` using the provided key, falling back to an `initialValue`. Any subsequent updates to the state using the returned `setValue` function automatically save the new value to `localStorage`, making data durable and accessible even after the user closes and reopens the browser.