Skip to content

Instantly share code, notes, and snippets.

@Cheesetouched
Created September 24, 2023 08:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cheesetouched/accf8cb5a3cf2b04b101040cb1c59cb6 to your computer and use it in GitHub Desktop.
Save Cheesetouched/accf8cb5a3cf2b04b101040cb1c59cb6 to your computer and use it in GitHub Desktop.
Simple hook to perform optimistic updates with react-query
import { useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
export default function useOptimisticUpdate() {
const queryClient = useQueryClient();
return useCallback(
async (queryKey, updater) => {
await queryClient.cancelQueries({ queryKey });
const previous = queryClient.getQueryData(queryKey);
queryClient.setQueryData(queryKey, updater);
return previous;
},
[queryClient],
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment