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.