JAVASCRIPT
Custom React Hook for Local Storage Persistence
A React hook to seamlessly synchronize component state with the browser's local storage, ensuring data persistence across sessions. Ideal for settings, user preferences, or form data.
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.error(error);
return initialValue;
}
});
// useEffect to update local storage when the state changes
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error(error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// Example Usage:
// function App() {
// const [name, setName] = useLocalStorage('name', 'John Doe');
// return (
// <input
// type="text"
// value={name}
// onChange={(e) => setName(e.target.value)}
// />
// );
// }
How it works: This `useLocalStorage` hook allows a React component's state to be persisted in the browser's local storage. It initializes the state by attempting to retrieve a value from local storage using the provided key, falling back to an `initialValue` if nothing is found or an error occurs. The `useEffect` hook ensures that whenever the state value changes, it is automatically serialized to JSON and saved back to local storage, providing data persistence across browser sessions.