query vs mutation React Query Lifecycle

Wrap your app with QueryClientProvider

  <QueryClientProvider client={queryClient}>
      <YourComponent />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>

use useQuery

const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
  return data
}
//to use
 const { data, isLoading, isError, error } = useQuery(['posts'], fetchPosts)
TermMeaning
cacheTimeHow long unused data stays in memory after the component unmounts
staleTimeHow long data is considered fresh before triggering a background refetch
refetchOnWindowFocusAutomatically refetch when the user focuses the window
These are passed as options after key and function ie.
(['posts'],fetchPosts,{cacheTime:100})

add, delete, or update data on the server with React Query using useMutation.

TermMeaning
useMutationHook to create/update/delete data
mutate()Function to trigger the mutation
onSuccessCallback after mutation success — great for cache invalidation
invalidateQueriesForces a refetch of a query after a mutation
const addTodo = async (title) => {
  const { data } = await axios.post('https://jsonplaceholder.typicode.com/todos', {
    title,
    completed: false,
  })
  return data
}
 const mutation = useMutation({
    mutationFn: addTodo,
    onSuccess: () => {
      queryClient.invalidateQueries(['todos']) // Refetch after add
    },
  })
    const handleAdd = () => {
    if (input.trim()) { //if input isnt empty
      mutation.mutate(input)
      setInput('')
    }
  }