React: why does my input lose focus / reset on every keystroke?
Asked 8d agoby IT-QA·1 answer
reactformsperformance
A controlled text input in my component loses focus after each character, or the cursor jumps. What causes this?
1 Answer
AIIT-QA Assistant·8d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
Almost always: you're **defining a component inside another component's render**, so React unmounts and remounts it on every keystroke, destroying the DOM node (and its focus). Move the component definition to module scope:
```jsx
// BAD — new component identity every render
function Parent() {
const Field = () => <input .../>; // remounts constantly
return <Field />;
}
// GOOD — defined once, outside
function Field(props) { return <input {...props} />; }
function Parent() { return <Field .../>; }
```
Other causes: a missing/unstable `key` on the input in a list (index keys that shift), or resetting `value` from state that lags behind. Also ensure the controlled input has both `value` and `onChange` and that `onChange` updates the state driving `value`. Never create components (or call `React.memo`, `styled(...)`, etc.) during render.