
Learn how React Query manages server state in a React app, using a client cache as the source of truth and supporting refetch, prefetch, deduplication, retries, and mutations.
Explore how react query integrates into a larger app through a day spa reservation project, with beginner and advanced tracks, code, and prerequisites for react, hooks, testing, and restful APIs.
master fetching blog posts with react query, manage loading and error states, implement pagination and prefetching, and explore mutations, dev tools, and configuring a query client and provider.
Set up a React Query client and provider to enable useQuery hooks across the app, sharing a central query cache for descendants in a React server state management workflow.
Demonstrates creating useQuery to fetch posts from the json placeholder api, handling data, loading, and error states, and integrating with a query client in React Query.
Learn to manage loading and error states with useQuery by destructuring isLoading, isFetching, and isError, using early returns and loading indicators, and handling errors, retries, and the default three tries.
Learn to install and use React Query dev tools to inspect query status, keys, and data via the data explorer and the query explorer in development.
Explore stale time and gc time in React Query, showing how cached data becomes stale and is revalidated, while garbage collection time governs cache expiry.
Practice code quizzes to reinforce React Query concepts like query keys, pagination, prefetching, and mutations while finishing the blog Om Ipsum app.
Create a useQuery call to fetch comments by post id in the post detail component, handling loading and error states with a unique query key and an anonymous fetch function.
Use per-post query keys by including the post id in the query key to create separate caches for each post's comments, avoiding cross-post data and stale results.
Implement next and previous page navigation using react query pagination and current page state. Update query key to reflect page and pass it to fetch posts; plan prefetching for UX.
Prefetch data to fill the cache before navigation, keeping pages ready and avoiding loading delays; use the query client and prefetch query on page change to fetch the next page.
Understand the difference between isLoading and isFetching in react-query. isLoading shows only when there is no cached data; isFetching runs whenever the query executes, with prefetch caching data.
Explore how mutations simulate server updates via network calls to add, delete, or edit posts, and manage optimistic updates, cache changes, and query invalidation with react query useMutation.
Learn to implement a delete post action with useMutation, passing the post id to a mutation function that performs a delete request and provides user feedback during the mutation.
Illuminate the useMutation return value, using isPending, isError, and isSuccess to display loading, error, and success messages with css classes, and reset the mutation when switching posts.
Practice implementing a mutation to update a post title with a pre-written function, observe the mutation status (isPending, isError, isSuccess) in React Query, and note that no server update occurs.
Install react query, create a query client, wrap app with a query provider to expose hooks and cache; use useQuery to fetch, handle loading, manage stale time and cache time.
Implement infinite scroll with React Query useInfiniteQuery to fetch more data from the Star Wars API as the user scrolls, loading additional results.
Set up infinite swapi with React Query by installing React Query and dev tools, creating a query client and provider, and enabling infinite scroll for people and species.
Explore useInfiniteQuery versus useQuery, focusing on pages and pageParams, and how pageParam drives the next pages via the last page's next property.
Explore how use infinite query manages the flow from initial mount to fetching the first page, using the page param, get next page param, and fetch next page.
Learn to implement a useInfiniteQuery call by importing it, destructuring data, fetchNextPage, and hasNextPage; configure with a Star Wars people query key, pageParam-based query function, and getNextPageParam using lastPage.next.
Implement infinite scroll with useInfiniteQuery, using an infinite scroll component to load more data when needed, and map pages to render person data with name, hair color, and eye color.
Learn to implement loading and error handling for useInfiniteQuery, avoid undefined data, and provide user feedback with a fixed-position loading indicator and infinite scroll.
Update app.js to display infinite species using useInfiniteQuery and an initial species URL. Implement load more with getNextPageParam, map species data (name, language, average lifespan), and enable smooth infinite scroll.
Explore bidirectional infinite scrolling with React Query, using next and previous page parameters. The page param and has next page indicate when to fetch more data, via the component.
Set up React Query in a multi-page app using central error and loading callbacks and custom hooks for useQuery, illustrated by the Lazy Days Spa appointment system.
Explore the Lazy Days Spa app code structure, focusing on auth state management with JWTs, Axios setup, and React Query integration, while previewing hooks, components, and TypeScript notes.
Install TanStack React Query and its dev tools, exploring lazy loading for production, and add the ESLint plugin to enforce exhaustive dependencies, ensuring query keys account for all dependencies.
Set up React Query by creating and exporting a query client, wrapping the app with the query client provider inside the Chakra provider, and adding dev tools for server state management.
Build a custom hook useTreatments with React Query to fetch treatments data from the server via an Axios request to the /treatments endpoint on localhost:3030, reusable across treatments and staff.
Implement a fallback data strategy for use query by defaulting to an empty array, preventing undefined errors, and centralizing the loading indicator for all use query calls.
Update your app to a centralized loading indicator using the useIsFetching hook from react query, showing a spinner whenever any query is fetching.
Configure the onError callback in the query cache of a React Query client to display Chakra toasts for fetch errors, prevent duplicate messages, and surface server fetch issues.
Implement a custom React Query hook useStaff to fetch staff data via getStaff, return staff with a fallback and a query key, and rely on global loading and error handling.
Set up React Query for a larger app with a separate query client file and custom hooks like useTreatment and useStaff to centralize data access, loading, and error handling.
Explore adding data to the cache with prefetch query and set query data, and distinguish placeholder data from initial data in React Query.
Prefetch the treatments data on home page load to preload the cache for the treatments tab using the query client's prefetch query.
Prefetch treatments on home page by building a hook that populates cache with prefetchQuery. Use useQueryClient to access the query client and call the hook in the home render.
Explore how the useAppointments hook manages month-year state, prefetches adjacent months, and exposes an appointment date map to drive the calendar and filter all versus unreserved.
Implement useQuery for appointments, include a deliberate mistake, set a fallback, and pass year and month to the query function to fetch data, then inspect month update issues.
Improve data correctness in React Query by giving each month its own query key, enabling automatic and manual refetching, prefetching, and efficient invalidation to keep calendar data fresh.
Use useEffect within the useAppointments hook to prefetch the next month’s appointments via the query client, caching data for seamless navigation and avoiding race conditions.
Explore how to prefetch data and set query data, and manage placeholder or initial data to optimize the cache and refetch behavior.
Learn how to transform and filter data with React Query's select option in useQuery, filtering unavailable appointments and using useCallback to keep the function stable.
Implement a selector for the useStaff hook to filter staff by treatment using a pre-written filter by treatment function, enable radio button filtering, and leverage useCallback for React Query caching.
Learn how prefetching updates stale data from the server and prompts refetch decisions. Use options like refetch on mount, window focus, reconnect, and interval, or raise stale time to suppress.
Adjust refetch behavior in react query by extending stale time to 10 minutes and garbage collection to 15 minutes, and disable refetch on mount, focus, and reconnect. Prefetch settings must mirror use query settings to keep data fresh.
Apply global default refetch options for all queries via the query client, with per-query overrides; appointments override with zero stale time, limited cache, and a polling interval to stay current.
Override global React Query defaults for appointments by setting stale time to zero and enabling polling, ensuring up to date server data for appointments in a responsive user interface.
Poll the server with a refetch interval to automatically update the logged-in user's appointments, using the use user appointments hook and triggering refetches on mutations.
Explore the select option for filtering, useCallback to create a stable function that passes the triple equals test, and review refetch options and polling in React Query.
Explore integrating React Query with authentication, using dependent queries and enabled conditions, and employing query client methods like setQueryData and removeQueries for json web token flow stored in local storage.
Explore auth and user data hooks in a React Query app, including use login data, auth actions, and use user to fetch server data with the token.
Add a useQuery call to fetch the current user from the server using the user id and token from the auth context, with a generated key and an enabled guard.
Update the user cache on sign-in with setQueryData using a generated user key; clear it on sign-out by removing queries with the user prefix.
Update the auth flow by wiring setQueryData in the query cache to reflect sign-in and sign-out, enabling useQuery to fetch the correct user data from the server.
Add useQuery to fetch user appointments as a dependent query on a truthy user id, using an appointments key and clearing cache on sign out.
Explore how react query and auth manage the logged-in user with the useUser hook and a server data useQuery, setQueryData on sign-in, and removeQueries on sign-out.
Explore how mutations update server data, invalidate and refetch queries, and refresh the cache, while implementing optimistic updates, global loading indicators, and robust error handling for mutations.
Learn to reserve appointments using the useReserveAppointment mutation in React Query, calling a mutation function with appointment and user id, then display a success toast.
Learn to invalidate queries after a mutation with queryClient.invalidateQueries using a query key prefix. Invalidate appointments and user appointments to trigger refetches and update the UI without refreshing.
Write a use mutation to cancel appointments with an onsuccess handler that invalidates appointment queries via the query client, and optionally shows a toast on success.
Update the server user data with a patch mutation and refresh the react query cache by setting query data with the server response via the update user function on success.
Explore how including the token in the user query key fragments the cache in React Query, and learn to stabilize the key by excluding the token for consistent user data.
Learn how optimistic updates in React Query improve UI responsiveness by updating the UI before server responses, and how to manage mutation with useMutation, cache updates, and query invalidation.
Implement optimistic updates for updating user information using a mutation with useQueryClient, an exported mutation key, and on settled to invalidate queries, while displaying pending data during the mutation.
Explain how the useMutation hook provides a mutate function to update data, keep the client in sync by invalidating queries or updating the cache, and discuss optimistic updates.
Learn to test React Query with a user-centric approach using the React Testing Library, focusing on user interactions while covering queries, mutations, and custom hooks.
This lecture details setting up tests for react query with mock service worker and testing library, including V test and eslint, preparing for a query provider next.
Learn to unit test react query components by wrapping renders in a query client provider, generating isolated query clients per test, and using a custom render to supply providers.
Test rendered query data by making the test async to verify the query response from mock service worker, ensuring three headings contain massage, facial, or scrub.
Explore testing React Query components by wrapping them in a query client provider, using mock staff data and handlers to verify staff data rendering and error handling.
Test react query error handling by simulating server errors with mock service worker, verify the toast that says could not fetch data, and configure query client options to disable retries.
Test mutations in react query by using test server, wrap components in a query provider with a client, and trigger mutations to verify the toast while simulating a logged-in user.
test custom hooks in react query using render hook, but prefer rendering the component that uses the hook; test filtering of appointments with a provider wrapper and query client.
Test the use appointments hook to verify filtering when show all toggles. Use a fresh query client wrapper and renderHook with wait for async results.
Test the custom use staff hook with react query server state management by filtering staff data, using mocks and a dedicated query client wrapper to validate results.
Test user interactions, not internals, by wrapping components in a query provider and using a separate test query client with production defaults, and suppress retries to test errors.
Version 5 update released!
As of January 2024, this course covers React Query version 5.
--
React Query (also called TanStack Query) has become the go-to solution for server state management in React apps, and for good reason! This smart, comprehensive solution makes it easy to keep your app up-to-date with data on the server.
In fact, if you are using Redux simply to manage data from the server, React Query can replace Redux in your app. And, for server data management, React Query is much simpler and more powerful than Redux. For example, React Query:
tracks loading and error states for your server queries (no need to manage that yourself!)
makes cached server data available for display while you're fetching updated data
This course starts with a simple app to learn the basics of React Query version 3:
queries
loading and error states
React Query dev tools
pagination and pre-fetching
mutations
Then we take a detour with the Star Wars API to learn about Infinite Queries (getting more data just as the user has gotten near the end of the current data).
Finally, we work on a large, multi-component app to learn about the above in more detail, plus
centralizing loading and error handling
filtering data
integrating React Query with auth
ways to keep data up to date after mutations, including optimistic updates
testing React Query
Other notable course features:
pre-written projects to use as a backdrop for React Query, so there's no time wasted writing code not relevant to the course
ample opportunities to practice with periodic "code quizzes" to make sure you're understanding the concepts
visual models for complicated concepts to help understand all of the moving pieces
the major project is written in TypeScript
supportive instructor who loves engaging with students in Q&A
Come see what the hype is about, and improve your apps with simpler, more powerful server state management!