> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xmonaco.com/llms.txt
> Use this file to discover all available pages before exploring further.

# useTokenLifecycle

> Persist and auto-refresh the authenticated session

```tsx theme={null}
import { useTokenLifecycle } from "@0xmonaco/react";

const {
  initializeTokens,
  clearTokens,
  refreshTokens,
  isTokenExpired
} = useTokenLifecycle(sdk, config);
```

Manages the lifecycle of the authenticated session: persists the session across reloads and refreshes it before it expires. The session is the wallet-authorized ed25519 keypair returned by `login()`; there are no separate access or refresh tokens. Most apps don't use this hook directly; `MonacoProvider` wires it up and `useAuth` drives it. See [React SDK setup](/sdk/react/intro).

## Parameters

<ParamField path="sdk" type="MonacoSDK | null" required>
  Monaco SDK instance from `useMonacoSDK()`
</ParamField>

<ParamField path="config" type="TokenLifecycleConfig">
  Session lifecycle options:

  * `autoRefresh`: boolean (default: `true`) - automatically extend the session before it expires
  * `persistTokens`: boolean (default: `true`) - persist the session in `localStorage` so it survives reloads
  * `refreshBufferSeconds`: number (default: `300`) - how long before expiry to trigger a refresh
  * `onRefreshError`: `(error: Error) => void` - called when a refresh fails
  * `onRefreshSuccess`: `(authState: AuthState) => void` - called when a refresh succeeds
</ParamField>

## Return Values

<ResponseField name="initializeTokens" type="(authState: AuthState) => void">
  Start managing a session. Call after a successful `login()`; persists the session (if enabled) and schedules auto-refresh.
</ResponseField>

<ResponseField name="clearTokens" type="() => void">
  Stop managing the session, cancel scheduled refreshes, and remove the persisted session. Call on logout.
</ResponseField>

<ResponseField name="refreshTokens" type="() => Promise<AuthState | null>">
  Extend the session's expiry now (via `sdk.refreshAuth()`). Returns the updated `AuthState`, or `null` if there is no active session or the refresh fails.
</ResponseField>

<ResponseField name="isTokenExpired" type="(authState: AuthState | null) => boolean">
  Whether the session is expired or within the refresh buffer of expiry.
</ResponseField>

## Example

```tsx theme={null}
import { useMonacoSDK, useTokenLifecycle } from "@0xmonaco/react";

function SessionManager() {
  const { sdk } = useMonacoSDK();

  const {
    initializeTokens,
    clearTokens,
    refreshTokens,
    isTokenExpired
  } = useTokenLifecycle(sdk, {
    autoRefresh: true,
    persistTokens: true,
    refreshBufferSeconds: 300, // refresh 5 minutes before expiry
    onRefreshError: (error) => {
      console.error('Session refresh failed:', error);
      // Handle logout or re-authentication
    },
    onRefreshSuccess: (authState) => {
      console.log('Session extended to', authState.expiresAt);
    },
  });

  // After a successful login
  const handleLoginSuccess = (authState) => {
    initializeTokens(authState);
  };

  // On logout
  const handleLogout = () => {
    clearTokens();
  };

  // Manual refresh if needed
  const handleManualRefresh = async () => {
    const newAuthState = await refreshTokens();
    if (!newAuthState) {
      console.log('Refresh failed, need to re-authenticate');
    }
  };

  return (
    <div>
      <button onClick={handleManualRefresh}>Refresh Session</button>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}
```

## How It Works

1. **Auto Refresh**: when enabled, schedules a session refresh `refreshBufferSeconds` before expiry.
2. **Persistence**: saves the session to `localStorage` so it can be restored after a reload.
3. **Deduplication**: collapses concurrent refresh calls into a single request.
4. **Cleanup**: clears scheduled timers on unmount.

<Warning>
  When `persistTokens` is enabled, the persisted session includes the ed25519 **session private key**. This credential signs every request. `localStorage` is readable by any script on your origin, so harden against XSS (e.g. a strict Content Security Policy) and always `clearTokens()` on logout. Disable `persistTokens` to keep the session in memory only.
</Warning>

<Note>
  This is an advanced hook. For most apps, `MonacoProvider` + `useAuth` manage the session automatically.
</Note>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.