JAVASCRIPT
Persist React State in Local Storage with useLocalStorage Hook
Learn how to create a custom React hook to automatically synchronize component state with browser local storage, ensuring data persistence across user sessions.
import { 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];
}
// How to use it:
// function App() {
// const [name, setName] = useLocalStorage('myName', 'Guest');
// return (
// <div>
// <input
// type="text"
// value={name}
// onChange={(e) => setName(e.target.value)}
// />
// <p>Hello, {name}!</p>
// </div>
// );
// }
How it works: This custom hook `useLocalStorage` allows you to manage component state that automatically persists to and loads from the browser's local storage. It initializes the state by attempting to retrieve the value from local storage; if not found or an error occurs, it falls back to a provided `initialValue`. The `useEffect` hook ensures that whenever the state `value` or `key` changes, the new value is stringified and saved to local storage, making the data persistent across browser sessions.