Install

npm
npm i use-any-hook

Description

The useLocalStorageWithExpiry hook allows you to store data in the browser’s localStorage with an expiration time. This is useful when you need to cache data temporarily and want it to be automatically removed after a certain period. The hook manages the storage and retrieval of data, ensuring that expired data is not used.

Parameters

NameTypeDescription
keystringThe key under which the data is stored in localStorage.
initialValueanyThe initial value to be stored. This can be of any type.
expiryTimenumberThe time in milliseconds after which the stored value will expire and be removed from localStorage.

Return Values

NameTypeDescription
valueanyThe current value stored in localStorage. If the stored value has expired, this will be null.
setStoredValue(value: any) => voidA function to update the value in localStorage and reset the expiry time.

Example

useLocalStorageWithExpiry.example.tsx
import { useLocalStorageWithExpiry } from "use-any-hook";

function MyComponent() {
  const [data, setData] = (useState < string) | (null > "");

  const { value, setStoredValue } = useLocalStorageWithExpiry(
    "key",
    "initialValue",
    3000
  ); // Expire after 3 seconds

  useEffect(() => {
    if (value) {
      // Use the retrieved data
      console.log("Data from localStorage:", value);
      setData(value); // Set the component state with retrieved data
    }
  }, [value]);

  const handleSaveData = (newData: string) => {
    setData(newData);
    setStoredValue(newData);
  };

  return (
    <div>
      <input value={data || ""} onChange={(e) => setData(e.target.value)} />
      <button onClick={() => handleSaveData(data)}>Save Data</button>
    </div>
  );
}