0

I have one local variable that is controlled by useState that should be set after calling useCallback. However, after debug I do not see the info is set. Looking for different solution in stackoverflow. but still do not know how to fix it

import { useCallback, useState } from "react";
import "./styles.css";

export default function App() {
  const [info, setInfo] = useState<object>({});
  const handleOnClick = useCallback(() => {
    console.log(info);//{}
    setInfo({ name: "name1", address: "1234" });
    console.log(info);//{}
  }, [info]);
  return (
    <div className="App">
      <button onClick={handleOnClick}>Hello</button>
    </div>
  );
}

jacobcan118
  • 7,797
  • 12
  • 50
  • 95
  • That second `console.log()` will not have the new value at that time. It has to wait for the batched update that React does under the hood. – zero298 Aug 10 '21 at 15:38
  • Add a debugging `useEffect(() => console.log(info), [info])` to make sure it changes. – zero298 Aug 10 '21 at 15:39

0 Answers0