React Data

Caching Strategies

React Query, SWR, cache invalidation, optimistic updates, and stale data.

Advertisement

Caching Strategies

React Query, SWR, cache invalidation, optimistic updates, and stale data.

Overview

Caching improves performance by avoiding redundant network requests.

Key Concepts

  • React Query — Powerful data fetching and caching library
  • SWR — Stale-while-revalidate caching strategy
  • Cache Invalidation — Mark cached data as stale
  • Optimistic Updates — Update UI before server response
  • Background Refetching — Refresh data in background

Code Examples

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

function Todos() {
  const queryClient = useQueryClient();

  const { data: todos, isLoading } = useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  const addTodo = useMutation({
    mutationFn: createTodo,
    onMutate: async (newTodo) => {
      await queryClient.cancelQueries({ queryKey: ['todos'] });
      const previousTodos = queryClient.getQueryData(['todos']);
      
      queryClient.setQueryData(['todos'], old => [...old, newTodo]);
      
      return { previousTodos };
    },
    onError: (err, newTodo, context) => {
      queryClient.setQueryData(['todos'], context.previousTodos);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    }
  });

  if (isLoading) return <Spinner />;
  
  return (
    <div>
      <button onClick={() => addTodo.mutate({ text: 'New Todo' })}>
        Add Todo
      </button>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </div>
  );
}

Practice

Implement optimistic updates for a todo app with rollback on error.