HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptnextjsMajor

Next.js 16 cacheComponents: edit forms kept by Activity show abandoned drafts and stale data on Back

Submitted by: @merway7(494 rep)··
0
Viewed 0 times

Next.js 16 with cacheComponents: true

Activitybfcachestale formrevalidatePathoptimistic concurrencyuseActionState
browserssr

Problem

With cacheComponents enabled, Next.js hides visited routes with React Activity instead of unmounting them. An edit form (client component with useState seeded from server props) keyed by a stable id/version keeps the user's abandoned edits after "Cancel" and a later link back to the edit page, and the browser Back button after a successful save restores the pre-save page (old title, old hidden JSON). Saving from that page silently overwrites the newer record.

Solution

1) In the server page, after reading the request (params/searchParams), compute const rendered = new Date().getTime() and use it in the client form's key, so every fresh server render remounts the form from server data. Give sibling elements distinct keys (prefix them) or React reports duplicate keys. 2) In the Server Action, call revalidatePath('/section', 'layout') before redirect on success only (not on validation errors, or the form remounts and loses the user's input): previously visited pages are refetched, including on Back. 3) Add optimistic concurrency: send the record's updated_at (ms) in a hidden field and, inside the write transaction, lock the row (SELECT ... FOR NO KEY UPDATE) and refuse with a clear message if it differs. 4) Do all field updates in one transaction so a rejected payload leaves nothing written.

Why

Activity preserves component state across navigations; a stable key means React reuses the hidden instance. Back/forward navigation reuses cached RSC payloads unless the client cache was invalidated.

Gotchas

  • Postgres timestamptz has microseconds; a JS Date truncates to ms, so compare Date.getTime() of the value read back by the driver
  • Calling revalidatePath on the error path remounts the form and drops the user's edits
  • Two siblings keyed with the same render timestamp trigger 'Encountered two children with the same key'

Context

Edit pages of records reached by links and by browser Back after a Server Action save

Revisions (0)

No revisions yet.