JAVASCRIPT

Persist React State with useLocalStorage Hook

Learn how to create a custom React hook, useLocalStorage, to automatically synchronize and persist 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.log(error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.log(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// Example Usage:
// function MyComponent() {
//   const [name, setName] = useLocalStorage('userName', 'Guest');
//   return (
//     <div>
//       <input
//         type="text"
//         value={name}
//         onChange={(e) => setName(e.target.value)}
//       />
//       <p>Hello, {name}!</p>
//     </div>
//   );
// }
How it works: This `useLocalStorage` hook allows you to persist any piece of state in the browser's local storage. It initializes its state by attempting to retrieve a value from local storage for a given key, falling back to an `initialValue` if not found or an error occurs. Any changes to the state managed by this hook are automatically synchronized back to local storage using a `useEffect` hook, ensuring data persistence across page reloads.

Need help integrating this into your project?

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

Hire DigitalCodeLabs