JAVASCRIPT
Persist React State with a useLocalStorage Custom Hook
Create a useLocalStorage custom hook in React to automatically synchronize and persist component state with the browser's local storage across page reloads.
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 Settings() {
// const [userName, setUserName] = useLocalStorage('userName', 'Guest');
// const [isDarkMode, setIsDarkMode] = useLocalStorage('isDarkMode', false);
// return (
// <div>
// <p>Hello, {userName}!</p>
// <input
// type="text"
// value={userName}
// onChange={(e) => setUserName(e.target.value)}
// placeholder="Your Name"
// />
// <button onClick={() => setIsDarkMode(!isDarkMode)}>
// Toggle Dark Mode: {isDarkMode ? 'On' : 'Off'}
// </button>
// </div>
// );
// }
How it works: The `useLocalStorage` hook allows you to persist a React state value in the browser's `localStorage`. It initializes the state by attempting to retrieve the value from `localStorage`; if not found, it uses the provided `initialValue`. A `useEffect` hook then automatically updates `localStorage` whenever the state `value` changes, ensuring data persistence across sessions or page reloads. Error handling is included for robust data storage.