JAVASCRIPT
Custom Hook: useLocalStorage for Persisting State
Learn to create a custom React hook, useLocalStorage, to effortlessly persist and retrieve component state in the browser's local storage 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];
}
// Example Usage:
// function MyComponent() {
// const [name, setName] = useLocalStorage('userName', 'Guest');
// return (
// <div>
// <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
// <p>Hello, {name}!</p>
// </div>
// );
// }
How it works: The `useLocalStorage` hook allows you to persist any state in the browser's local storage. It initializes the state by attempting to read from local storage, falling back to an initial value if nothing is found or an error occurs. An `useEffect` hook then ensures that whenever the state changes, it's automatically saved to local storage, providing seamless persistence for user preferences or data.