•5 min read

React Input Cursor Jumps to the End: Count the Writes

Support forwarded a ticket about our order search field last week. "I can't fix a typo in the middle," the customer wrote. "Every character throws my cursor to the end." I reproduced it in under five seconds and blamed the formatter that spaces the digits in groups of four. That was half an answer, and the wrong half cost me an afternoon.

What sorted it out was counting. React writes to that input more often than anyone expects, and every write with a different string drops the caret at the end. Patch the value setter and the writes announce themselves:

const d = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')
Object.defineProperty(HTMLInputElement.prototype, 'value', {
  configurable: true,
  get: d.get,
  set(v) {
    console.log(this.id, JSON.stringify(d.get.call(this)), '->', JSON.stringify(v), 'caret', this.selectionStart)
    d.set.call(this, v)
  },
})

React goes through the same setter, so nothing hides from it. One keystroke per case, React 19.3.1 production build, headless Chrome 158, the field holding 1234 5678 with the caret at offset 4:

what the field doeswritescaret after
plain controlled input, typed 705
digits-only formatter111, end of string
formatter, typed Z (rejected)19, end
state applied one task later210, end
Close up of fingers on a white keyboard, typing

Zero writes, caret untouched

The first row rearranged my head. Nothing got written. React compared the string it wanted against the one already in the DOM and left the element alone.

The whole mechanism is one comparison in react-dom's updateInput:

element.value !== "" + getToStringValue(value) &&
  (element.value = "" + getToStringValue(value));

React isn't preserving anything here. It skips the assignment when the text matches, and the browser keeps the selection where the user left it. The moment your string differs by one character, React assigns value and the browser moves the caret to the end, because the old offset no longer points at the same place.

Row three is the one I show people. I typed a letter into a digits-only field, the formatter threw it away, and the text ended up identical to what was on screen a keystroke earlier. The caret still finished at the end.

The second write is React undoing your typing

Row four is what you get when you debounce the state update, wrap it in startTransition, or sync from a parent. Two writes for one Z:

write "1234Z 5678" -> "1234 5678"   caret 5 -> 9
write "1234 5678" -> "1234Z 5678"   caret 9 -> 10

The first write puts the old string back. That's restoreStateOfTarget running at the end of the event and writing the last committed props value into the node. With a synchronous update, "last committed" is exactly what the user typed, the strings match, and nothing gets written. With a late update React doesn't know what the user typed yet, so it restores stale text, and your update lands a task later and overwrites it.

The final string is exactly what I typed, so diffing before and after shows nothing. The caret is the only evidence, which is why this takes two days to find.

So my first check is a plain controlled input: if the caret survives there, the bug is my transform or my async update.

Restoring selectionStart lands one character short

The standard advice: capture selectionStart in onChange, set it back after the commit. Do that and you land one position left of the user whenever a separator moved past the caret, which is the case that matters.

Typing 7 at offset 4 of 1234 5678 gives raw 12347 5678. Formatted, that's 1234 7567 8. The saved offset was 5, the correct one is 6, because a separator moved to the other side of the caret. Restore 5 and the cursor sits before the digit you just typed. Type again and you insert in front of it.

Count digits instead of characters, then walk the formatted string until that many digits have gone by:

function digitsBefore(s, upto) {
  let n = 0
  for (let i = 0; i < upto && i < s.length; i++) if (/\d/.test(s[i])) n++
  return n
}

function caretForDigits(formatted, n) {
  let seen = 0
  for (let i = 0; i < formatted.length; i++) {
    if (/\d/.test(formatted[i]) && ++seen === n) return i + 1
  }
  return formatted.length
}

Typing works after that. Backspace still doesn't. Put the caret after a separator and press backspace: the space gets reinserted, the formatted string equals the current state, React bails out of the render, and a useLayoutEffect restore never runs. Measured: caret 9, digit still in the box.

The restore has to land after that write, so a microtask is the earliest safe slot:

onChange={(e) => {
  const n = digitsBefore(e.target.value, e.target.selectionStart)
  const next = group(e.target.value)
  const pos = caretForDigits(next, n)
  setValue(next)
  queueMicrotask(() => ref.current?.setSelectionRange(pos, pos))
}}

Three cases, three correct carets: 6 after a keystroke, 4 after a rejected letter, 4 after backspace.

Composition is where it stops being cosmetic

Composing ni into the digits-only input: React fires onChange on every composition update, the formatter returns an empty string, React writes it back, and the pinyin is gone while the user is still picking a candidate. Two compositionstart events for one composition, because the write tore the first one down. The plain input beside it took the same input with zero writes and kept composing.

The guard is a ref, not state, so flipping it doesn't schedule a render in the middle of a composition.

const composing = useRef(false)

onCompositionStart={() => { composing.current = true }}
onCompositionEnd={(e) => {
  composing.current = false
  setValue(group(e.target.value))
}}
onChange={(e) => {
  if (composing.current) return
  /* map the caret, set the value, restore in a microtask */
}}

What I do instead

Most fields don't need live formatting. Formatting on blur removes this whole class of bug, and the card-number field is the only one I've kept, because people really do check digits in fours. Where formatting stays, I count digits for the caret, restore in a microtask, and skip everything while composing.

I also stopped deferring input state. A debounced setState behind a text field is a caret bug with a delayed fuse. If you're reaching for useDeferredValue to keep a list off the keystroke, put the caret on your test list too.

The write counter and the digit mapping live in Snippet Ark, mostly so I don't retype the loop from memory next year. The counter is the part worth keeping: two minutes of patching a setter tells you which row you're in, and the fix stops being mysterious.