Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 24.9 — Offline Support, Caching and Persistence
React · Example 3 of 3

Offline detection, a saved draft and an outbox

The script fires the browser's offline event, adds two notes (they wait in the outbox), then fires online: the outbox is sent in order. The draft in the input is saved on every change. Real code would persist the outbox too (IndexedDB) so it survives a reload.

A resilient app keeps copies of data in layers (memory, localStorage, IndexedDB, the HTTP cache and a service worker), shows cached data at once and refreshes it in the background (stale-while-revalidate), updates the screen optimistically and rolls back on failure, notices when the network goes away, and saves drafts and queued actions so nothing the user typed is lost.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a usePersistentState(key, initial) hook that works like useState but saves to localStorage, safely.

02

Add a "You're offline" banner to any app using useSyncExternalStore.

Explain it without notes

01

Compare memory, localStorage, IndexedDB, the HTTP cache and service workers as caching layers.

02

What is stale-while-revalidate and why does it improve UX?

03

How do you implement an optimistic update safely?

04

How would you make a form work offline without losing data?

Offline detection, a saved draft and an outbox

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

In the tunnel: Offline: notes will be sent later | Sent: none · Waiting: 2
Back online: Online | Sent: Buy milk, Call Asha · Waiting: 0