JAVASCRIPT
Persist React State to Local Storage with a Custom Hook
Build a custom React hook, `useLocalStorage`, to automatically synchronize and persist component state with the browser's local storage, ensuring data persists across page reloads.
import React, { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
const [value, setValue] = 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(value));
} catch (error) {
console.error(error);
}
}, [key, value]);
return [value, setValue];
}
// Example Component Usage:
function UserSettings() {
const [username, setUsername] = useLocalStorage('username', 'Guest');
const [notificationsEnabled, setNotificationsEnabled] = useLocalStorage('notifications', true);
return (
<div>
<h1>User Settings</h1>
<label>
Username:
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</label>
<br />
<label>
<input
type="checkbox"
checked={notificationsEnabled}
onChange={(e) => setNotificationsEnabled(e.target.checked)}
/>
Enable Notifications
</label>
<p>Hello, {username}! Notifications: {notificationsEnabled ? 'On' : 'Off'}</p>
</div>
);
}
export default UserSettings;
How it works: The `useLocalStorage` custom hook combines `useState` and `useEffect` to create a state variable that automatically persists its value in the browser's local storage. On initial render, it attempts to load the value from local storage; if not found, it uses the provided `initialValue`. The `useEffect` hook ensures that whenever the state value changes, it is asynchronously saved to local storage, making the data persistent across browser sessions.