JAVASCRIPT

Persist React State with a useLocalStorage Hook

Create a custom React hook, useLocalStorage, to automatically synchronize component state with the browser's local storage, ensuring data persistence.

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 UserSettings() {
//   const [theme, setTheme] = useLocalStorage('appTheme', 'dark');
//   const [fontSize, setFontSize] = useLocalStorage('appFontSize', 16);

//   return (
//     <div>
//       <p>Current Theme: {theme}</p>
//       <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>Toggle Theme</button>
//       <p>Font Size: {fontSize}px</p>
//       <button onClick={() => setFontSize(fontSize + 1)}>Increase Font</button>
//     </div>
//   );
// }
How it works: The `useLocalStorage` hook allows you to store and retrieve component state from the browser's local storage, making it persistent across page reloads. It initializes state by attempting to parse a value from local storage, falling back to an `initialValue` if nothing is found or an error occurs. A `useEffect` hook then watches for changes to the `storedValue` and updates local storage accordingly, ensuring the state and storage remain synchronized.

Need help integrating this into your project?

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

Hire DigitalCodeLabs