JAVASCRIPT
Synchronize React State with Local Storage
A custom React hook to store and retrieve state directly from browser's local storage, ensuring data persistence across page reloads for enhanced user experience.
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 reading from local storage:', error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error('Error writing to local storage:', error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// Example Usage:
// import React from 'react';
// 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: This hook provides a simple yet robust way to store and retrieve a state value directly from `localStorage`. It initializes the state by attempting to parse a stored item, falling back to an `initialValue` if nothing is found or an error occurs. Any changes to the state automatically update `localStorage`, ensuring data persists even after the user leaves and returns to the page.