Optimistic updates are a powerful feature in React Query that allows applications to update the UI before receiving a server response, providing a smoother user experience.
How to Implement Optimistic Updates
In React Query, implementing optimistic updates with the useMutation hook involves these basic steps:
-
Configure useMutation:
javascriptconst mutation = useMutation(updateTodo, { // Optimistic update function onMutate: async (updatedTodo) => { // 1. Cancel duplicate requests for related queries await queryClient.cancelQueries('todos'); // 2. Get current cached data as rollback state const previousTodos = queryClient.getQueryData('todos'); // 3. Optimistically update the cache queryClient.setQueryData('todos', (oldTodos) => oldTodos.map((todo) => todo.id === updatedTodo.id ? updatedTodo : todo ) ); // 4. Return rollback function return { previousTodos }; }, // Error handling, rollback data onError: (err, updatedTodo, context) => { queryClient.setQueryData('todos', context.previousTodos); }, // Regardless of success or failure, refetch latest data onSettled: () => { queryClient.invalidateQueries('todos'); }, }); -
Call mutation:
javascriptmutation.mutate({ id: 1, title: 'Updated Todo' });
Advantages of Optimistic Updates
- Better user experience: Users see immediate feedback after actions without waiting for server responses
- Reduced perceived latency: UI responds quickly even with slow network connections
- Closer to native app experience: Fast operation responses feel more fluid
- Simplified state management: No need to manually manage loading states and temporary UI states
Disadvantages of Optimistic Updates
- Increased implementation complexity: Requires more code to handle optimistic updates and rollback logic
- Potential data inconsistency: If server requests fail, users may see updated UI then rollback
- Need to consider concurrent operations: Conflicts may occur if multiple optimistic updates happen simultaneously
- Increased debugging difficulty: Issues may appear in optimistic update logic, rollback logic, or server response handling
Best Practices
- Suitable for simple operations: Optimistic updates work best for simple CRUD operations like updating task status or editing text
- Provide visual feedback: Can show temporary status indicators like loading animations after optimistic updates
- Handle errors properly: Ensure data is correctly rolled back on server failures and error messages are displayed to users
- Consider network conditions: May need to adjust optimistic update strategies in unstable network environments
Optimistic updates are a double-edged sword - when used correctly, they can significantly improve user experience, but require careful handling of various edge cases.