react-query
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
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
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)
fetchStatus vs status:
status: It can be one of the following values:
loading,error,success, oridlefetchStatus: It can be
fetching,paused, oridle
Parallel queries: useQueries() hook
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 likevariables.idorvariables.title)when updating, make sure to invalidationQueries the whole list and updated item
await invalidateQueries({ queryKey: [‘todos‘] })await invalidateQueries({ queryKey: [‘todo‘, { id: variables.id }] })
Pagination
export function useProjects(page: number) {
return useQuery({
queryKey,
queryFn,
placeholderData: keepPreviousData
})
}isPlaceholderData: check if return data is placeholder data
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;
}
})
}isFetchingNextPagehasNextPage
REFERENCE: