CodePark/ questions / Rendering & reconciliation
START PRACTICINGPRACTICE
Frontend question · React › Rendering & reconciliation

What does the user experience when typing in this input?

function Form() {
  const [text, setText] = useState('');

  function TextInput() {
    return <input value={text} onChange={e => setText(e.target.value)} />;
  }

  return <TextInput />;
}
The input loses focus after every keystroke

The input loses focus after every keystroke. TextInput is a new function every time Form renders. So React sees a different component type at that position. It unmounts the old one and mounts a new one, creating a fresh <input> that has no focus.

"It works normally" is the tempting wrong answer, because the code looks fine. React does not throw either: defining a component inside a component is legal JavaScript. Declare components at the top level of the file and pass data as props.