Type a message to Ada, then switch to Linus. A key makes React start a fresh Chat so the draft is not sent to the wrong person.
React · intermediate · 8 min · 22 steps · free
import { useState } from 'react';
function Chat({ contact }) {
const [draft, setDraft] = useState('');
return (
<div>
<p>To: {contact}</p>
<input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Message" />
</div>
);
}
export default function Messenger() {
const [to, setTo] = useState('Ada');
return (
<div>
<button onClick={() => setTo(to === 'Ada' ? 'Linus' : 'Ada')}>Switch contact</button>
<Chat key={to} contact={to} />
</div>
);
}<Messenger> for the first time: it calls the Messenger function.useState runs for the first time, so React stores the starting value for to and returns it: "Ada".Messenger returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.<Chat> for the first time: it calls the Chat function. Its props: contact = "Ada".useState runs for the first time, so React stores the starting value for draft and returns it: "".Chat returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onChange handler.setDraft(e.target.value) does not change draft right away: React queues the update and will render again. In this call draft is still "".useState returns the value React has kept for draft: "Hi Ada". The starting value is only used on the first render.Chat returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.setTo(to === 'Ada' ? 'Linus' : 'Ada') does not change to right away: React queues the update and will render again. In this call to is still "Ada".<Messenger> again (render 2): it calls Messenger once more, from the top.useState returns the value React has kept for to: "Linus". The starting value is only used on the first render.Messenger returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.draft starts again at "".Chat returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: Kept. Same place, same type.
Answer: Change its key
← Stale Closures · Derived State: Calculate, Don't Store →