React Resetting State
Choose whether a switch preserves a draft or starts a new one, and make that choice visible.
How it works
React retains state by component identity and position. A key can deliberately say that a different record deserves a fresh component instance. Here a note belongs to the selected item. Switching the item resets the draft because Draft is keyed by item ID. That is a product decision, not a trick for forcing random rerenders. If users expect unsent drafts per item, store those drafts by ID instead.
Run the code
Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.
No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.
Example
import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';
function Draft({ item }) {
const [note, setNote] = useState('');
return (
<label>
Note for {item}
<input value={note} onChange={(event) => setNote(event.target.value)} />
</label>
);
}
function App() {
const [item, setItem] = useState('basket');
return (
<main>
<h1>Neighbourhood lending desk</h1>
<button
onClick={() => setItem((value) => (value === 'basket' ? 'stool' : 'basket'))}
>
Switch item and clear draft
</button>
<Draft key={item} item={item} />
</main>
);
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);
Expected result
After text is entered, switching items clears it and names the newly selected item.
The button label warns about the reset. A new key makes React discard the earlier Draft state and mount a new instance. Stable keys normally preserve identity in lists; here a changing domain identity deliberately ends it. Do not make a new random key on every render, which would erase typing while the user is still editing.
For API contracts and version differences, use React’s official documentation.