JAVASCRIPT

How to persist React state with useLocalStorage hook

Build a custom React useLocalStorage hook to effortlessly store and retrieve component state from the browser's localStorage, maintaining data across sessions.

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 ThemeSwitcher() {
//   const [theme, setTheme] = useLocalStorage('app-theme', 'light');
//
//   const toggleTheme = () => {
//     setTheme(theme === 'light' ? 'dark' : 'light');
//   };
//
//   return (
//     <button onClick={toggleTheme}>Toggle Theme: {theme}</button>
//   );
// }
How it works: The useLocalStorage hook initializes state by attempting to retrieve a value from localStorage, falling back to an initial value if none is found or an error occurs. A useEffect hook then synchronizes changes to the state with localStorage, ensuring data persistence across page reloads and 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