JAVASCRIPT

Custom Hook for Local Storage State

Implement a React custom hook to effortlessly persist and retrieve component state from the browser's local storage, ensuring user preferences and form data survive page reloads.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    if (typeof window === 'undefined') {
      return initialValue;
    }
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      const valueToStore = typeof storedValue === 'function'
        ? storedValue(storedValue) // handle functional updates
        : storedValue;
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// Example usage:
// function ThemeToggle() {
//   const [theme, setTheme] = useLocalStorage('app-theme', 'light');

//   const toggleTheme = () => {
//     setTheme(theme === 'light' ? 'dark' : 'light');
//   };

//   return (
//     <button onClick={toggleTheme}>
//       Switch to {theme === 'light' ? 'dark' : 'light'} Theme
//     </button>
//   );
// }
How it works: The `useLocalStorage` hook provides a convenient way to synchronize a piece of component state with the browser's local storage. When the component mounts, it attempts to load the value from local storage; if not found, it uses the provided `initialValue`. Any subsequent updates to this state using the returned `setStoredValue` function will automatically be persisted to local storage, making the data persistent across browser sessions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs