JAVASCRIPT
Persist React State to Local Storage
Learn how to create a custom React hook, `useLocalStorage`, to effortlessly synchronize and persist your component's state with the browser's local storage.
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];
}
export default useLocalStorage;
// Example Usage:
// function ThemeToggler() {
// const [theme, setTheme] = useLocalStorage('appTheme', 'light');
//
// const toggleTheme = () => {
// setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
// };
//
// return (
// <div>
// <p>Current theme: {theme}</p>
// <button onClick={toggleTheme}>Toggle Theme</button>
// </div>
// );
// }
How it works: This `useLocalStorage` hook allows you to store and retrieve state directly from the browser's local storage. It initializes state by attempting to parse an existing value from local storage or using a provided initial value. Any changes to the state are automatically persisted to local storage using a `useEffect` hook, ensuring data survives page refreshes, making it ideal for features like theme toggling or user preferences.