REACT

useLocalStorageWithExpiry Hook

A custom React Hook for persisting state to localStorage with expiration time and TypeScript support

ReactHooksLocalStorageCache

Code

import { useState, useEffect } from 'react';

type StoredValue<T> = {
  value: T;
  expiry: number | null;
};

function useLocalStorageWithExpiry<T>(
  key: string,
  initialValue: T,
  expiryInMinutes = 60
): [T, (value: T | ((val: T) => T)) => void, () => void] {
  // Get initial value (check expiry)
  const [storedValue, setStoredValue] = useState<T>(() => {
    __TOKEN_18__ (typeof window === 'undefined') return initialValue;

    try {
      const item = window.localStorage.getItem(key);
      __TOKEN_23__ (!item) return initialValue;

      const parsed = JSON.parse(item) as StoredValue<T>;
      // Check if expired
      __TOKEN_26__ (parsed.expiry && Date.now() > parsed.expiry) {
        window.localStorage.removeItem(key);
        return initialValue;
      }
      return parsed.value;
    } __TOKEN_29__ (error) {
      console.warn(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });

  // Update localStorage with expiry
  const setValue = (value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      __TOKEN_35__ (typeof window !== 'undefined') {
        const expiry = expiryInMinutes ? Date.now() + expiryInMinutes * 60 * 1000 : null;
        window.localStorage.setItem(key, JSON.stringify({ value: valueToStore, expiry }));
      }
    } __TOKEN_38__ (error) {
      console.warn(`Error setting localStorage key "${key}":`, error);
    }
  };

  // Clear stored value
  const clearValue = () => {
    __TOKEN_40__ (typeof window !== 'undefined') {
      window.localStorage.removeItem(key);
      setStoredValue(initialValue);
    }
  };

  return [storedValue, setValue, clearValue];
}

// Usage example
// const [token, setToken, clearToken] = useLocalStorageWithExpiry('auth-token', '', 15);
// const [preferences, setPreferences] = useLocalStorageWithExpiry('user-prefs', { theme: 'light' }, 1440);