JAVASCRIPT
Persist State to Local Storage with useLocalStorage
Create a custom `useLocalStorage` hook in React to automatically persist and retrieve component state from the browser's local storage.
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, 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]); // Only re-run if key or storedValue changes
return [storedValue, setStoredValue];
}
// Example Usage:
function LocalStorageCounter() {
const [count, setCount] = useLocalStorage('my-counter-key', 0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default LocalStorageCounter;
How it works: The `useLocalStorage` custom hook provides a convenient way to persist component state in the browser's `localStorage`. It initializes its state by attempting to retrieve a value from `localStorage` using a provided `key`, falling back to an `initialValue` if nothing is found or an error occurs. An `useEffect` hook then automatically updates `localStorage` whenever the `storedValue` changes, ensuring that the state is saved across page reloads. This encapsulates the logic for interacting with `localStorage` into a reusable, declarative pattern.