I have the following custom hook that basically fetches data from a smart contract:
export const usePoolLength = () => {
const [length, setLength] = useState(0);
const _getPoolLength = useCallback(async () => {
const poolLength = await getPoolLength();
setLength(poolLength);
}, [])
useMemo(() => {
_getPoolLength();
}, [_getPoolLength]);
return { length }
}
export const getPoolLength = async () => {
const poolLength = await masterchefV2Contract.poolLength();
return poolLength.toNumber();
}
I understand that calling an API is a side effect but should I be using useEffect
or useMemo
? It seems like there is no difference so I’m not thinking about changing to useEffect
. Wanted to get some opinions/advise, thank you!
4
Answers
The
useCallback
/useMemo
combination here seems a little tangled.useEffect
is more straightforward, perhaps easier to read:I think it is clearly mentioned in the docs:
Also consider the fact that
_getPoolLength
is not being used anywhere else. It is a method that is only useful for the API call so why not define it inside the effect and use it there only.Why do you actually use
useCallback
withuseMemo
in combination withuseState
?I think you should just use the
useMemo
hook like this:As long as your custom hook doesn’t need to refetch the data.