← Back to all snippets
JAVASCRIPT

Persist State with the useLocalStorage Hook

Implement a useLocalStorage React hook to easily store and retrieve component state in the browser's local storage, ensuring data persists across page reloads.

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 reading from local storage:", error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error("Error writing to local storage:", error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}
/*
// Example usage:
function ThemeToggler() {
  const [theme, setTheme] = useLocalStorage('app-theme', 'light');

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

  return (
    <div style={{ background: theme === 'dark' ? '#333' : '#FFF', color: theme === 'dark' ? '#FFF' : '#333', padding: '20px' }}>
      <h1>Current Theme: {theme}</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}
*/
How it works: The useLocalStorage hook allows you to store and retrieve state from `localStorage`. It initializes its state by attempting to parse a value from `localStorage` using the provided `key`, falling back to `initialValue` if nothing is found or an error occurs. An `useEffect` hook then ensures that whenever the `storedValue` changes, it's automatically serialized to JSON and saved back into `localStorage`, making the state 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