JAVASCRIPT

React useLocalStorage Hook for Persistent State

Persist and retrieve React state seamlessly using local storage with this custom hook, ideal for user preferences or session management.

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.warn(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });

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

  return [storedValue, setStoredValue];
}
How it works: The `useLocalStorage` hook allows you to store and retrieve state directly from the browser's `localStorage`. It initializes the state by attempting to read from the specified `key`; if not found, it uses the `initialValue`. Any subsequent changes to the state automatically persist to `localStorage`, making it excellent for remembering user settings, theme preferences, or other persistent data across sessions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs