Skip to content

QuizNot attempted

Lazy initializer captures the first value

The user types "hello" into the input over several keystrokes. What does the <p> show?
function Form() {
const [text, setText] = useState('hi');
const [list, setList] = useState(() => [text]);
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<p>{list.join(',')}</p>
</div>
);
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • hi
  • The lazy initializer () => [text] runs only on mount, capturing text as 'hi'
  • later changes to text never touch list, so it shows hi.
  • Not hello: list isn't derived from text on each render.
  • Not hi,hello: nothing ever appends to list.
  • Not empty: the initializer did run once.
  • If you want a derived value, compute it during render instead of storing it.