Home > Blockchain >  Want to understand the dependency in usecallback
Want to understand the dependency in usecallback

Time:10-10

    const [balance, setBalance] = useState();
    const pollBalance = useCallback(async (provider, address) => {
        if (provider && address) {
            const newBalance = await provider.getBalance(address);
            if (!newBalance.eq(balance !== null && balance !== void 0 ? balance : zero)) {
                setBalance(newBalance);
                console.log(address, newBalance.toString(), balance);
            }
        }
    }, [balance]);

As I understand this UseCallBack Hook . The PollBalance function will only get callled if the balance changes right otherwise it will use the previous state itself

But I am changing my balance state inside of the function right ? using setBalance(newBalance) . So technically that means my pollBalance will never get caled because my balance never changes right?

CodePudding user response:

The PollBalance function will only get callled if the balance changes right

So technically that means my pollBalance will never get caled because my balance never changes right?

The code you've shown has nothing to do with calling pollBalance, it's just about creating pollBalance. If the values in the dependency array have changed, then a new function is created and assigned to the variable pollBalance. If they havn't changed, then pollBalance will be assigned the previous function and the new function is thrown out.

Whether pollBalance gets called or not depends on if you have a line of code that looks like pollBalance(someProvider, someAddress), which was not included in the code you showed.

P.S, since your new state depends on your old state, I recommend you switch to using the function version of setBalance. This will also let you remove balance from the dependency array:

const [balance, setBalance] = useState();
const pollBalance = useCallback(async (provider, address) => {
  if (provider && address) {
    const newBalance = await provider.getBalance(address);
    setBalance((prev) => {
      if (!newBalance.eq(prev !== null && prev !== void 0 ? prev : zero)) {
        console.log(address, newBalance.toString(), prev);
        return newBalance;
      } else {
        return prev;
      }
    });
  }
}, []);

CodePudding user response:

You have misconception about useCallback hook,And its this

As I understand this UseCallBack Hook . The PollBalance function will only get callled if the balance changes right otherwise it will use the previous state itself

First thing useCallback is for creating a callback,You can write a function inside your functional component without using useCallback. But problem with this way is every time your function component will re-render you will have new reference to same function,If you are passing such a function to any other child component then it will may cause that child component to re-render as reference of function is changed in props. To over come with this use case we have useCallback. So by using useCallback hook ,you are creating a function not calling it. And every time balance will change your refence to function will change. Which you are storing in PollBalance (indirectly you are redefining same function with updated dependencies).While using useCallback hook , every value referenced inside the callback should also appear in the dependencies array.because if you dont do so ,call back will use older values,here in your code you will need to pass both balance, setBalance in dependency array.

const pollBalance = useCallback(async (provider, address) => {
if (provider && address) {
    const newBalance = await provider.getBalance(address);
    if (!newBalance.eq(balance !== null && balance !== void 0 ? balance : zero)) {
        setBalance(newBalance);
        console.log(address, newBalance.toString(), balance);
    }
}
}, [balance,setBalance]);

and make call to pollBalance on some event like button click or something ,it will not called automatcally.

Hope this will help.

  • Related