0

I was very mistaken about the behavior of useCallback hook. I was under the impression that let's say if I had a code like this

const [value1, setValue1] = useState(null);
const [value2, setValue2] = useState(null);
const [value3, setValue3] = useState(null);

const foo = useCallback(() => console.log(value1, value2, value3), [value1, value2, value3])

and if I call a function that looks like this

function bar() {
   setValue1(1);
   setValue2(2);
   setValue3(3);

   foo();
}

I should always get a copy of the function foo that has all the updated dependencies. Which means the output should be

1 2 3

But it isn't. It's

null null null

So I'm using the useCallback hook wrong. Is there a hook that does what I want from a useCallback hook?

Vipul Rajan
  • 494
  • 1
  • 5
  • 16
  • can you share the entire code where "bar" is implemented? – lante Mar 31 '23 at 20:44
  • @vipul, calling `setValue1` does not (and can not) change the value in the local const `value1`, so `foo` also can't see that new value. `setValue1` just asks react to rerender the component. On that new render you'll create new local variables, but code from your old render has no access to those. I suggest you rework the `foo` function so you can pass values into it, as in `foo(1, 2, 3)`. Then you can manually pass in the values which you just updated the state to be. – Nicholas Tower Mar 31 '23 at 20:49

0 Answers0