~/swaraj.dev
Back to all posts
March 26, 20261 min read

Optimistic UI Updates with React Query in React Native

Learn how to make your React Native app feel instantly responsive by applying optimistic updates with React Query, reducing perceived latency while keeping data consistent.

react queryoptimistic updatesreact nativestate management

Insight

In mobile apps, waiting for a server round‑trip can feel sluggish. React Query’s optimistic update pattern lets you update the UI before the mutation succeeds, then roll back on error. This approach works beautifully in React Native because the UI thread isn’t blocked, and the library handles cache reconciliation automatically.

Example

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { updateTodo } from './api';

function useOptimisticTodo(id: string) {
  const queryClient = useQueryClient();
  return useMutation(updateTodo, {
    // Apply UI change immediately
    onMutate: async (newTodo) => {
      await queryClient.cancelQueries(['todo', id]);
      const previous = queryClient.getQueryData(['todo', id]);
      queryClient.setQueryData(['todo', id], newTodo);
      return { previous };
    },
    // Restore on failure
    onError: (_err, _newTodo, context) => {
      queryClient.setQueryData(['todo', id], context?.previous);
    },
    // Refetch after success
    onSettled: () => queryClient.invalidateQueries(['todo', id]),
  });
}

Takeaway

Wrap your mutations with onMutate, onError, and onSettled to give users instant feedback. Remember to cache the previous state so you can revert gracefully if the server rejects the change.