JAVASCRIPT
Custom useLocalStorage Hook for React State Persistence
Persist React state in the browser's local storage with this custom hook. Automatically synchronize state changes and retrieve initial values on component mount.
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.log(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
How it works: The `useLocalStorage` hook provides a way to persist React state in `localStorage`. It initializes state by trying to parse an existing item from `localStorage` or using a provided `initialValue`. The `setValue` function updates both the component's state and the `localStorage` item, ensuring data consistency across sessions. It also handles function updates to the state, similar to `useState`.