Introducing a new way to perform optimistic updates
When performing optimistic updates, you must always be careful about the changes you make to your cache. One typo or mistake might accidentally impact other queries outside of the one you want to change initially.
Fortunately, with v5, TanStack Query has introduced a way to perform optimistic updates where you can fully rely on your UI and stop changing your cache.
Let us see how:
export const NewOptimisticMutation = () => { const [name, setName] = useState(""); const [age, setAge] = useState(0); const queryClient = useQueryClient(); const { data } = useQuery({ queryKey: userKeys.all(), queryFn: fetchAllData, retry: 0, }); const mutation = useMutation({ mutationFn: createUser, onSettled: () => ...