react-query

  1. staleTime vs cacheTime:

  • if staleTime=1s, the data is considered as fresh for 1s. After 1s, it's stale data and refetch new data because no cache left

  • if cacheTime=1s, the data is cached for 1s. After 1s, it will refetch new data because no cache left

→ if cacheTime < staleTime? staleTime=15s, cacheTime=5s, go to another page for 10s, when get back, cannot get cached data because cacheTime < 10s => will have to manual refetch, after cacheTime expires, cached data will be auto removed


  1. How React-query cache:

  • React Query caches data in the browser’s memory, which is essentially the RAM allocated to the browser. This means that the cached data is stored in a JavaScript object in memory. When you reload the browser, the memory is cleared, which is why the cached data is lost


  1. Invalidation:

  • Invalidation in react-query: set data as stale (if data being used/active then auto refetch the new data, else will fetch new data next time)


  1. fetchStatus vs status:

  • status: It can be one of the following values: loading, error, success, or idle

  • fetchStatus: It can be fetching, paused, or idle


  1. Parallel queries: useQueries() hook


  1. Lifecycle of mutation:

onMutate → mutateFn → onSuccess / onError → onSettled

  • onSettled(data, error, variables)

    • variables can access to individual field in data

    (for example data = { id: 1, title: “Hello” } then we can access like variables.id or variables.title )

  • when updating, make sure to invalidationQueries the whole list and updated item


    await invalidateQueries({ queryKey: [‘todos‘] })

    await invalidateQueries({ queryKey: [‘todo‘, { id: variables.id }] })


  1. Pagination

export function useProjects(page: number) {
 return useQuery({
  queryKey,
  queryFn,
  placeholderData: keepPreviousData
 })
}
  • isPlaceholderData : check if return data is placeholder data


  1. Infinite Scroling

export function useProjects(page: number) {
 return useInfiniteQuery({
  queryKey,
  queryFn,
  initialPageParam: 0,
  getNextPageParam: (lastPage, allPages, lastPageParam) => {
   if (lastPage.length === 0) {
    return undefined;
   }

   return lastPageParam + 1;
  },
  getPreviousPageParam: (firstPage, allPages, firstPageParam) => {
   if (firstPageParam <= 1) {
    return undefined;
   }

   return firstPageParam - 1;
  }
 })
}
  • isFetchingNextPage

  • hasNextPage


REFERENCE: