> ## Documentation Index
> Fetch the complete documentation index at: https://use-any-hook-d92674ab.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# useLocalStorageWithExpiry

> Persist data in localStorage with an expiry time using useLocalStorageWithExpiry.

#### **Install**

```bash npm theme={null}
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**

| Name         | Type   | Description                                                                                         |
| ------------ | ------ | --------------------------------------------------------------------------------------------------- |
| key          | string | The key under which the data is stored in localStorage.                                             |
| initialValue | any    | The initial value to be stored. This can be of any type.                                            |
| expiryTime   | number | The time in milliseconds after which the stored value will expire and be removed from localStorage. |

#### **Return Values**

| Name           | Type                 | Description                                                                                     |
| -------------- | -------------------- | ----------------------------------------------------------------------------------------------- |
| value          | any                  | The current value stored in localStorage. If the stored value has expired, this will be `null`. |
| setStoredValue | (value: any) => void | A function to update the value in localStorage and reset the expiry time.                       |

#### **Example**

```javascript useLocalStorageWithExpiry.example.tsx theme={null}
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>
  );
}
```
