JAVASCRIPT
Custom Hook for Synchronizing State with Local Storage
Develop a React custom hook to automatically synchronize component state with local storage, ensuring data persistence across sessions and simplifying user preference management.
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 it works: This `useLocalStorage` hook behaves like `useState` but persists its value in the browser's local storage. It initializes its state by attempting to retrieve a value from local storage, falling back to an `initialValue` if none is found or an error occurs. Any changes to the state are automatically written back to local storage, providing data persistence across browser sessions.