🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ 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.

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement