← Back to all snippets
JAVASCRIPT

Persisting State with a `useLocalStorage` Hook

Implement a custom React `useLocalStorage` hook to automatically synchronize component 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];
}

// Example Usage:
// function MyComponent() {
//   const [name, setName] = useLocalStorage('userName', 'Guest');
//   return (
//     <input
//       type="text"
//       value={name}
//       onChange={(e) => setName(e.target.value)}
//       placeholder="Enter your name"
//     />
//   );
// }
How it works: This hook manages state that persists across browser sessions using `localStorage`. It initializes state by trying to retrieve a value from `localStorage` and uses `useEffect` to save the current state to `localStorage` whenever it changes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs