Advanced React Interview QuestionsAdvancedScenario
React · Question 75
Why should a controlled text input's value update not be placed inside a Transition?
Direct answer
Controlled input state must update synchronously with the user's typing; instead, update the input state urgently and defer the expensive UI that depends on it.
SearchPage.jsx
function SearchPage() {
const [query, setQuery] = useState("");
const [resultsQuery, setResultsQuery] = useState("");
const [isPending, startTransition] = useTransition();
function handleChange(event) {
const nextQuery = event.target.value;
setQuery(nextQuery); // urgent: controls the input
startTransition(() => {
setResultsQuery(nextQuery); // non-urgent
});
}
return (
<>
<input value={query} onChange={handleChange} />
<Results query={resultsQuery} />
</>
);
}React requires the state controlling the input's value to track each keystroke immediately. The expensive result view is the part that can be deprioritized.