0

Can someone explain why the output of following code is 0 and not 666? I'm assuming onSuccess callback is somehow using stale data, but I don't think that is desirable.

import "./styles.css";
import { useQuery, useMutation } from "react-query";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const { mutate } = useMutation(
    [count],
    () => {
      return new Promise((resolve) => {
        setTimeout(() => resolve("data"), 5000);
      });
    },
    {
      onSuccess: (data) => {
        console.log(count);
      }
    }
  );

  return (
    <div className="App">
      <button
        onClick={() => {
          mutate();
          setTimeout(() => {
            setCount(666);
          }, 2000);
        }}
      >
        Button
      </button>
    </div>
  );
}

I expect onSuccess to use latest value for count state variable

Priyanshu
  • 35
  • 1
  • 1
  • 5
  • Please check [this thread](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately). – ivanatias Dec 23 '22 at 22:05
  • The same code works if I use refetch and useQuery combination. Not sure if mentioned thread is relevant here – Priyanshu Dec 23 '22 at 22:15
  • That's not how closures work in react. In a function, you'll always see the value from the time the function was created. I'm trying to explain this here: https://tkdodo.eu/blog/hooks-dependencies-and-stale-closures – TkDodo Dec 25 '22 at 18:53

0 Answers0