Performance: Optimistic updates pattern
This pattern affects interaction responsiveness and perceived speed by updating the UI before server confirmation.
function handleClick() {
setState(newData); // update UI immediately
fetch('/api/update', { method: 'POST' }).then(response => {
if (!response.ok) {
rollbackState(); // revert UI if error
}
});
}async function handleClick() { const response = await fetch('/api/update', { method: 'POST' }); if (response.ok) { setState(newData); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Waiting for server response before UI update | 1 per update after response | 1 reflow per update | Moderate paint cost | [X] Bad |
| Optimistic UI update before server response | 1 immediate update, possible rollback | 1 reflow per update | Moderate paint cost | [OK] Good |
optimistic updates pattern in Remix Framework?useFetcher?fetcher.submit(data) to send data.handleClick is called?const [count, setCount] = useState(0);
const fetcher = useFetcher();
function handleClick() {
setCount(count + 1); // optimistic update
fetcher.submit({ count: count + 1 }, { method: 'post' });
}setCount(count + 1) updates the UI state immediately by adding 1.function addTodo(newTodo) {
const previousTodos = todos;
setTodos([...todos, newTodo]); // optimistic update
fetcher.submit({ todo: newTodo }, { method: 'post' });
}newTodo to the list.fetcher.submit() does not return a Promise and there is no useEffect or other logic to check fetcher.state or fetcher.data for errors and revert the state.Pass the test and this pattern moves unknown