JAVASCRIPT
useLocalStorage Hook for Persisting State
Discover how to create a custom React `useLocalStorage` hook to easily persist and retrieve component state in the browser's local storage, ensuring data persistence 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 ThemeSwitcher() {
// const [theme, setTheme] = useLocalStorage('appTheme', 'light');
// const toggleTheme = () => {
// setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
// };
// return (
// <button onClick={toggleTheme}>
// Switch to {theme === 'light' ? 'dark' : 'light'} Theme
// </button>
// );
// }
How it works: The `useLocalStorage` hook provides a convenient way to synchronize a React state variable with an item in `localStorage`. It initializes its state by attempting to parse a value from `localStorage` or falling back to an `initialValue`. An `useEffect` hook then ensures that whenever the state (`storedValue`) changes, the new value is stringified and saved to `localStorage`, making the state persistent across browser sessions.