Course contentsShow
← React
Lesson 1266 of 2,39632. Lists and Keys Deep DiveFree lesson

Focus Loss and Cursor Jumps

How bad keys cause focused elements to lose focus or text cursors to jump to unexpected positions.

Focus Loss and Cursor Jumps

You'll learn: How unstable keys cause focused elements to lose focus or text cursors to jump to unexpected positions during re-renders.

The Problem

When you're typing in an input field within a list item and the list re-renders with unstable keys (like array indices), React can't tell which component is which anymore. This causes the focused element to lose focus entirely, or worse, the text cursor to jump to strange positions—making your form feel completely broken.

Why This Happens

Think of keys like name tags at a conference. If everyone's name tag changes every time someone enters the room, you'd lose track of who you were talking to mid-conversation. Similarly, when keys change:

  1. React unmounts the old component (with your focus)
  2. Mounts a "new" component (even though it's the same data)
  3. The DOM element is recreated, losing focus and cursor position
// BAD: Typing in an input causes cursor jumps
{items.map((item, index) => (
  <input key={index} defaultValue={item.name} />
))}

// GOOD: Focus and cursor position preserved
{items.map((item) => (
  <input key={item.id} defaultValue={item.name} />
))}

With index keys, sorting or filtering the list reassigns keys to different items. An input that was key={0} might become key={2}, forcing React to destroy and recreate it.

Real Impact

Users typing in a todo list suddenly lose focus after every keystroke. Cursors jump to the end of input fields. Forms become unusable because focus bounces around randomly—all because keys aren't stable.

Key Takeaway: Unstable keys break focus management and cursor positioning because React destroys and recreates DOM elements instead of updating them in place. Always use stable IDs as keys for any list containing interactive elements.