I don't understand why I'm getting infinite loop in useClick I see that I change state value inside useEffect using setVal but useEffect should work only on onClick as specified in second param. I thought that it is because the param onClick i pass is memoized but the callback is not called(i checked that using console.log('go set')
function useClick(onClick, setVal, val) {
React.useEffect(() => {
console.log('Click');
setVal(val + 1);
}, [onClick]);
}
const Home = () => {
const [val, setVal] = React.useState(0);
const incrementOnClick = React.useCallback(() => {
console.log('go set');
setVal(val + 1);
} , [setVal, val]);
useClick(incrementOnClick, setVal, val);
return <div>
<div>{val}</div>
<button onClick={incrementOnClick}>Click me</button>
</div>
}
useClickinsideHomeComponent:HomecallsuseClick, insideuseClickyou change thevalproperty ofHome, thus theHomeComponent` it's re-rendered, thus the functionHomeit's called again, thususeClickis executed again.. And there is the loop - JollyHomegets rendered your going to get another instance ofincrementOnClick, so passing that as the last parameter touseEffectis not going to do anything. - Keith