JAVASCRIPT
React Hook: useLocalStorage for Persisting State
A `useLocalStorage` custom hook for React that automatically synchronizes component state with the browser's localStorage, 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];
}
// How to use it:
/*
function UserSettings() {
const [theme, setTheme] = useLocalStorage('app-theme', 'light');
const [userName, setUserName] = useLocalStorage('user-name', '');
return (
<div>
<h3>Theme: {theme}</h3>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
<h3>User Name: {userName}</h3>
<input
type="text"
value={userName}
onChange={(e) => setUserName(e.target.value)}
placeholder="Enter your name"
/>
</div>
);
}
*/
How it works: The `useLocalStorage` hook initializes its state using a function passed to `useState`. This function attempts to retrieve a value from `localStorage` based on the provided `key`, parsing it from JSON, or falls back to `initialValue`. An `useEffect` then runs whenever `storedValue` or `key` changes, saving the current state into `localStorage`. This ensures the component's state is persistent across browser sessions.