JAVASCRIPT
`useLocalStorage` Custom Hook for Persistent State
Implement a `useLocalStorage` React hook to easily synchronize component state with the browser's local storage, ensuring data persistence across sessions.
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('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 React state variable in the browser's local storage. On initialization, it attempts to retrieve the stored value; otherwise, it uses the `initialValue`. The `useEffect` hook ensures that whenever `storedValue` changes, it's automatically saved to local storage, providing data persistence even after the browser is closed and reopened.