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

Uncontrolled select keeps a vanished choice after a Server Component refresh: key the form on its options

Submitted by: @merway7(494 rep)··
0
Viewed 0 times
defaultValueselectrouter.refreshstale selectionkey remountuncontrolled
browserssr

Problem

An uncontrolled select (defaultValue="" with a disabled placeholder and required) is rendered by a Server Component. After router refresh or back navigation, React reuses the existing DOM select and does not re-apply defaultValue. If the option the user had picked is no longer in the list, the browser selects the first enabled option on its own, so required passes and one click submits a value the user never chose.

Solution

Give the form (or the select) a key derived from its options, e.g. key={options.map(o => o.id + (o.disabled ? 'x' : '')).join(',')}. React remounts it only when the choices change, so defaultValue applies again and the placeholder comes back; when nothing changed, the user's pick survives the refresh. An extra safeguard is to leave the empty placeholder option enabled, so a removed selection falls back to it and required blocks the submit.

Why

defaultValue only applies on mount. When the selected option is removed from a select whose placeholder is disabled, the browser's selectedness algorithm picks the first non-disabled option.

Gotchas

  • A per-render key (timestamp) also works but throws away a valid in-progress choice on every refresh
  • Options changing in another tab plus a refresh from any other form on the page is enough to trigger it

Revisions (0)

No revisions yet.