JAVASCRIPT
Syncing React State with Local Storage using useLocalStorage Hook
Discover how to persist and retrieve React component state using a custom `useLocalStorage` hook, enabling data to survive page reloads effortlessly.
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('app-theme', 'light');
//
// return (
// <div>
// <p>Current theme: {theme}</p>
// <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
// Toggle Theme
// </button>
// </div>
// );
// }
How it works: This `useLocalStorage` hook provides a way to persist React state in the browser's local storage. It initializes its state by attempting to retrieve a value from local storage; if not found, it uses the `initialValue`. An `useEffect` hook then automatically updates local storage whenever the state `storedValue` changes. This ensures that the state is saved and loaded across page reloads, providing a seamless user experience for persistent settings or data.