javascript / expert
Snippet
Optimistic UI Updates with State Rollback
Optimistic UI assumes a server request will succeed and updates the interface immediately to feel instantaneous. However, handling failures is mandatory. This pattern captures the previous state before the update, allowing for a seamless rollback if the asynchronous operation fails, ensuring data integrity.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const useOptimisticAction = (onSync) => {const [data, setData] = useState(initialData);const execute = async (payload) => {const previousData = data;setData(prev => ({ ...prev, ...payload })); // Optimistictry {await onSync(payload);} catch (err) {setData(previousData); // Rollback on failureconsole.error('Sync failed, rolling back.');}};return [data, execute];};
react
Breakdown
1
const previousData = data;
Snapshotting current state to enable restoration in case of network error.
2
setData(prev => ({ ...prev, ...payload }));
Immediate UI update before the async call starts.
3
setData(previousData);
Restoring the original state if the try-catch block catches a rejection.