refetch: It will run the query again, but it will check the cache first. If the data is available, then it will return it from cache; else, it makes an api call and gets the new data and caches it.
<button onClick=()=>refetch()> refetch</button>
Note: if you use the isPending state for display a loading state, and you expect to display the Loading state whenever you click on the Refetch button, but it will not display the loading state because the isPending state gives true very first time only(if there is no cache data). You can also solve this issue by replacing idPending with isFetching.
Conditional querying: it's not going to run every time React re-renders the component. It is useful in cases where you have multiple useQueries in the same component and you only need certain ones depending on some time in your component.
const condition= true
const {data, isPending}= useQuery<>({
queryKey:["products"],
queryFn:getProducts,
enable:condition
})
Reusable Queries:
import {queryOptions} from "@tanstack/react-query"
export function postQueries(){
return queryOptions({
queryKey:["products"],
queryFn:getProducts,
})
}
Note: we extract it into a separate file, so now we can use this whenever we want in any possible component, and we made it modular and reusable.