KITFORMA · EDITORIAL ANSWER
Why does a memoized React callback submit an old record ID?
KitForma editorial guide. An empty useCallback dependency list retains the callback from the first render, including its original recordId.
Step-by-step answer
import { useCallback, useState } from "react";
export default function App() {
const [recordId, setRecordId] = useState("A");
const [savedId, setSavedId] = useState("none");
// Deliberately broken: retains the first render's recordId.
const saveStale = useCallback(() => setSavedId(recordId), []);
// Correct: a changed recordId creates the current handler.
const saveCurrent = useCallback(() => setSavedId(recordId), [recordId]);
return <>
<label>Record <select value={recordId}
onChange={event => setRecordId(event.target.value)}>
<option value="A">A</option><option value="B">B</option>
</select></label>
<button type="button" onClick={saveStale}>Save stale</button>
<button type="button" onClick={saveCurrent}>Save current</button>
<p role="status">Saved: {savedId}</p>
</>;
}Sources and verification
Sources checked:
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.