JAVASCRIPT

Persist State to Local Storage with a Custom React Hook

A custom React hook that synchronizes a piece of state with local storage, ensuring data persistence across page reloads for better user experience.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error, return initialValue
      console.error(error);
      return initialValue;
    }
  });

  // useEffect to update local storage when the state changes
  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

export default useLocalStorage;

// 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 store and retrieve state values from the browser's local storage. It initializes its state by attempting to parse a stored value from local storage, falling back to an `initialValue` if nothing is found or an error occurs. Any subsequent changes to this state are automatically synchronized with local storage using a `useEffect` hook.

Need help integrating this into your project?

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

Hire DigitalCodeLabs