Advanced React: onToggle event listener

Hi, in the “onToggle event listener” lesson from the Advanced React course, the callback is called from a “useEffect”, which also triggers the first time the component is rendered.

In the next lessons, this is solved by using refs, however, I was wondering: Could we just use the toggle function and call the callback from there?

So instead of:

React.useEffect(() => {
    onToggle()
}, [on])

just

function toggle() {
    setOn(prevOn => !prevOn)
    onToggle()
}

That way there is no need to use refs and it also won’t be triggered the first time the component is rendered.

Hey @Pablo, been a while since I did React so answering from memory. You technically can call onToggle() directly inside toggle() and it would work fine if the only way on ever changes is through that function. That also avoids the “runs on first render” issue you mentioned.

The catch is that setOn is async, so when you call onToggle() right after it, you’re technically still working with the old value of on. Also, if the state ever gets changed from somewhere else (like a reset button, prop change, etc.), your onToggle() won’t run, since it’s only wired to toggle().

I assume that’s why the course leans on useEffect([on]) + a ref. It makes sure the callback always runs in sync with the actual updated state, no matter how on gets changed.