JAVASCRIPT
Persist State with useLocalStorage Hook
Create a `useLocalStorage` React hook to easily persist and retrieve component state in the browser's local storage, ensuring data survives page refreshes.
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
const [value, setValue] = 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(value));
} catch (error) {
console.error(error);
}
}, [key, value]);
return [value, setValue];
}
// Example Usage:
// function UserSettings() {
// const [theme, setTheme] = useLocalStorage('appTheme', 'light');
// return (
// <div>
// <p>Current theme: {theme}</p>
// <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
// Toggle Theme
// </button>
// </div>
// );
// }
How it works: The `useLocalStorage` hook allows you to store and retrieve state directly from the browser's `localStorage`. It initializes its state by attempting to read from `localStorage` using the provided `key` and automatically updates `localStorage` whenever its state changes. This provides a simple way to persist data across page loads, enhancing user experience without manual handling of storage APIs.