🔍

Mastering Data Fetching with React Query

Aug 25, 2024

React Query Tutorial Notes

Introduction

  • In-depth tutorial on using the React Query library for data fetching in React applications.
  • React Query is preferred due to its powerful features and fewer resources available on YouTube.
  • Chapters available for easy navigation through the video.

Installation

  • Open terminal and run: yarn add @tanstack/react-query
  • The library was previously named just react-query.

Using React Query

Provider Setup

  • React Query is a data fetching and state management solution.
  • Use a QueryClient to manage shared data access across components.
  • In index.js:
    • Import QueryClient and QueryClientProvider from @tanstack/react-query.
    • Instantiate QueryClient and wrap the App component with QueryClientProvider.

Fetching Data with useQuery

  • Fetch data using useQuery hook.
  • Example API: JSON Placeholder (for fetching to-do data).
  • The useQuery hook handles:
    • Data fetching
    • Loading state
    • Error management
  • Syntax: const { data, error, isLoading } = useQuery( ['todos'], // Query key fetchTodos // Query function );
  • Use the fetch API to retrieve data: const fetchTodos = async () => { const response = await fetch('API_URL'); return response.json(); };

Rendering Data

  • Loop through fetched data using data.map().
  • Handle loading state and errors: if (isLoading) return <div>Loading...</div>; if (error) return <div>Error occurred!</div>;

Mutating Data with useMutation

Adding Posts

  • Use useMutation for creating or altering data.
  • Example: Adding a post using the same API.
  • Define mutation function and handle post requests: const addPost = async (newPost) => { const response = await fetch('API_URL', { method: 'POST', body: JSON.stringify(newPost), headers: { 'Content-Type': 'application/json' }, }); return response.json(); };
  • Call mutation function on button click: const { mutate } = useMutation(addPost); <button onClick={() => mutate(newPost)}>Add Post</button>

Caching and Invalidation

  • React Query manages a cache for query results.
  • Use queryClient.invalidateQueries to refetch data after a mutation: queryClient.invalidateQueries('posts');
  • Alternatively, manually update the cache using queryClient.setQueryData: queryClient.setQueryData('posts', (oldPosts) => [...oldPosts, newPost]);

Stale Time and Cache Time

  • Stale Time: Length of time a query is considered fresh. After this, it can be refetched automatically.
  • Cache Time: Determines when unused queries are garbage collected.
  • Recommended to set cache time longer than stale time.

Best Practices

  • Create query functions outside of components for better organization.
  • Avoid placing QueryClient inside components to prevent cache resets on re-renders.
  • Always check that React Query is set up properly in index.js.

Advanced Features

  • Support for parallel and dependent queries.
  • Manage query retries on failure (e.g., retry: 3).
  • Set general default options for all queries (e.g., stale time, cache time).

Conclusion

  • React Query simplifies data fetching and state management.
  • Encouraged to explore more use cases and features.
  • Video code will be shared for experimentation.

  • Thank you for watching! Don't forget to like and subscribe!