ЁЯУЛ

React Query Tool - Lecture Notes

Jul 12, 2024

React Query Tool Lecture

Introduction

  • A tool to make data fetching easier in applications.
  • Handles errors, retries, and caching automatically.
  • Enhances both user and developer experience.

Key Features of React Query

  • User Experience Increase: Instant data fetching without manual error handling or retries.
  • Developer Experience Increase: Reduces boilerplate code for handling data fetching operations.
  • Caching Mechanism: Reduces server load and enhances performance by caching queries.
  • Error Handling: Simplifies error handling in fetch requests.
  • Retry Mechanism: Automatically retries failed queries.

Setting Up React Query

  1. Installation: npm install react-query
  2. Initialization: import { QueryClient, QueryClientProvider } from 'react-query'; const queryClient = new QueryClient(); <QueryClientProvider client={queryClient}> <App /> </QueryClientProvider>

Basic Usage

  1. Fetching Data: Using useQuery: import { useQuery } from 'react-query'; const { data, isLoading, error } = useQuery('products', fetchProducts); const fetchProducts = async () => { const res = await fetch('/api/products'); return res.json(); };
  2. Fetching Single Product: const fetchProduct = async (id) => { const res = await fetch(`/api/products/${id}`); return res.json(); }; const { data, isLoading, error } = useQuery(['product', productId], () => fetchProduct(productId));
  3. Using Query Keys for Dynamic Fetching:
    • Useful in caching to ensure unique data for each query.
    • Example: ['product', id]

Advanced Features

  1. Automatic Refetching:
    • When window is focused.
    • Network is reconnected.
    • On interval using refetchInterval.
    useQuery('products', fetchProducts, { refetchInterval: 10000 });
  2. Pagination and Infinite Scroll:
    • Uses useInfiniteQuery for infinite scroll functionality.
  3. Error Handling and Loading States: Inline States: if (isLoading) return 'Loading...'; if (error) return 'An error occurred';
  4. Retries:
    • Automatic retry mechanism for failed requests.
    • Configurable retry count and delays.

Mutations (for Updates, Deletes, and Creates)

  1. Using useMutation: import { useMutation } from 'react-query'; const mutation = useMutation(newTodo => { return fetch('/todos', { method: 'POST', body: JSON.stringify(newTodo) }) });
  2. Example of Use Case: const { mutate, isLoading, error } = useMutation(updatedProduct => axios.put(`/products/${id}`, updatedProduct)); <button onClick={() => mutate({ id: 1, title: 'Updated Title' })}> Update Product </button>
  3. Optimistic Updates: const mutation = useMutation(updateTodo, { onMutate: newTodo => {}, onSuccess: data => {}, onError: (error, newTodo, context) => {}, onSettled: (data, error, newTodo, context) => {} });

Devtools

  • Installation: npm install react-query-devtools
  • Usage: import { ReactQueryDevtools } from 'react-query/devtools'; <QueryClientProvider client={queryClient}> <App /> <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider>
  • Provides a real-time insight into your queries and mutations.
  • Can simulate loading, error, and success states.

Important Configurations

  • Default Options: const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, staleTime: 10000, }, }, });
  • staleTime: Determines how long a query's data is considered fresh.
  • React Query in Production:
    • Efficient caching can significantly reduce server load.
    • Customize caching, refreshing, and retrying strategies as per need.

Conclusion

  • React Query is an effective tool for managing server-state in React applications, promoting both better user experience and simpler developer workflows.
  • Encouraged to start using React Query for server-state management over traditional methods like Redux for asynchronous operations.

References