# Critical app data is persisted across app lifecycle

- **Pattern:** `ab-001873` (`mobile-offline-storage.data-persistence.data-persisted-lifecycle`)
- **Severity:** critical
- **Lifecycle:** active
- **Last modified:** 2026-04-18
- **Canonical URL:** https://auditbuffet.com/patterns/ab-001873
- **License:** CC-BY-4.0 — attribute to AuditBuffet Pattern Catalog (https://auditbuffet.com/patterns/ab-001873)

## Why it matters

Persisting only an auth token while leaving user profile, form progress, and app state in memory creates a class of silent data loss that frustrates users and erodes retention. When the OS terminates your app — which happens routinely on low-memory devices — anything not written to storage is gone. ISO 25010:2011 reliability.recoverability requires that at least three critical data categories survive an unexpected termination. Apps that fail here force users to repeat onboarding flows, re-enter form data, and lose context — all of which correlate directly with abandonment.

## Severity rationale

Critical because in-memory-only state means any OS-triggered termination silently destroys user progress across multiple data categories with no recovery path.

## Remediation

Use an `AppState` listener to flush state to storage whenever the app moves to the background, and restore it on foreground return. Wrap both paths in try/catch so corrupted storage doesn't crash startup.

```tsx
import { useEffect, useRef, useState } from 'react';
import { AppState } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export function usePersistState<T>(key: string, initial: T) {
  const [state, setState] = useState<T>(initial);
  const appState = useRef(AppState.currentState);

  useEffect(() => {
    const sub = AppState.addEventListener('change', async (next) => {
      if (next.match(/inactive|background/)) {
        await AsyncStorage.setItem(key, JSON.stringify(state));
      } else if (appState.current.match(/inactive|background/) && next === 'active') {
        const saved = await AsyncStorage.getItem(key);
        if (saved) setState(JSON.parse(saved));
      }
      appState.current = next;
    });
    return () => sub.remove();
  }, [state]);

  return [state, setState] as const;
}
```

Apply this hook to every critical data category: user profile, navigation state, and any in-progress form inputs.

## Detection

**The detection method for this pattern is part of AuditBuffet Pro.**

The full method (what to look for, pass and fail conditions, and how results get reported) ships inside the [Mobile Offline & Storage Audit](https://auditbuffet.com/audits/mobile-offline-storage). The pattern definition, severity rationale, and remediation remain openly licensed under CC-BY-4.0.

## External references

- iso-25010 reliability.recoverability

Taxons: data-integrity

HTML version: https://auditbuffet.com/patterns/ab-001873
