JAVASCRIPT
Persist React State Across Page Loads with `useLocalStorage`
Discover how to build a `useLocalStorage` custom hook to effortlessly store and retrieve React component state, ensuring data persistence for a smoother user experience.
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');
// const toggleTheme = () => {
// setTheme(theme === 'light' ? 'dark' : 'light');
// };
// return (
// <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#333' : '#fff' }}>
// <h1>Current theme: {theme}</h1>
// <button onClick={toggleTheme}>Toggle Theme</button>
// </div>
// );
// }
How it works: The `useLocalStorage` hook allows you to persist a piece of React state in the browser's `localStorage`. It initializes its state by attempting to retrieve a value associated with a given `key` from `localStorage`. If no value is found, it uses the provided `initialValue`. Any subsequent changes to this state are automatically saved to `localStorage` using `useEffect`. This hook is perfect for maintaining user preferences, form data, or any application state that needs to persist even after the user closes and reopens the browser.