JAVASCRIPT
Persist State with a `useLocalStorage` React Hook
Create a custom `useLocalStorage` hook to effortlessly synchronize React component state with the browser's local storage for data persistence.
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.error(error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error(error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// Example Usage:
// function ThemeSwitcher() {
// const [theme, setTheme] = useLocalStorage('app-theme', '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 provides a convenient way to store and retrieve state from the browser's `localStorage`. It initializes the state by attempting to read from `localStorage` or uses a provided `initialValue`. An `useEffect` hook then ensures that whenever the state changes, the new value is automatically saved to `localStorage`, allowing data to persist across browser sessions.