πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Caching Strategies

React Data🟒 Free Lesson

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.

⭐

Premium Content

Caching Strategies

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement