Command Palette

Search for a command to run...

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

Optimistic like with rollback

Both clicks update the button at once. The first request succeeds; the second fails, so the button goes back to the last confirmed state and an alert explains why.

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?

Optimistic like with rollback

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Right after click 1: ♥ 42
Server said ok: ♥ 42
Right after click 2: ♡ 41
Server failed: ♥ 42 | Couldn't save: Server unavailable