JAVASCRIPT
Persist React State with Local Storage
Store and retrieve React state automatically from the browser's local storage, ensuring data persistence across page refreshes and browser sessions for user settings or preferences.
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(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.log(error);
}
};
return [storedValue, setValue];
}
// Example Usage:
// function ThemeToggler() {
// const [theme, setTheme] = useLocalStorage('appTheme', 'light');
// const toggleTheme = () => {
// setTheme(theme === 'light' ? 'dark' : 'light');
// };
// return (
// <button onClick={toggleTheme}>
// Switch to {theme === 'light' ? 'dark' : 'light'} theme
// </button>
// );
// }
How it works: The `useLocalStorage` hook allows you to persist a piece of state to the browser's `localStorage`. When initialized, it attempts to load the value from `localStorage` using the provided `key`; if not found or parsing fails, it defaults to `initialValue`. Any subsequent updates to the state via the `setValue` function automatically save the new value to `localStorage`, ensuring data persists even after the user closes and reopens the browser.