JAVASCRIPT
React `useLocalStorage` Hook for Persisted State
Learn to persist React state effortlessly across page refreshes using the `useLocalStorage` custom hook. Ideal for user preferences or theme settings.
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) {
console.log(error);
return initialValue;
}
});
// useEffect to update local storage when the state changes
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.log(error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// Example Usage:
// function ThemeSwitcher() {
// const [theme, setTheme] = useLocalStorage('theme', 'light');
// const toggleTheme = () => {
// setTheme(theme === 'light' ? 'dark' : 'light');
// };
// return (
// <button onClick={toggleTheme}>
// Switch to {theme === 'light' ? 'dark' : 'light'} theme
// </button>
// );
// }
How it works: This hook allows you to persist any state value in the browser's local storage. It initializes the state by attempting to retrieve the value from local storage; if not found, it uses the provided `initialValue`. An `useEffect` hook ensures that whenever the state changes, the new value is automatically saved to local storage, making it resilient to page refreshes.