One of the important things that we learn about useEffect is that we need to pass on dependency to the useEffect to make it run conditionally. But the useEffect runs on every hard refresh even after having a dependency. Let us understand this through an example and how to figure a workaround.
Here we have a state toggle and useEffect with toggle being passed as a dependency to the useEffect, which will console log "useEffect running" every time the toggle state changes. For the UI we have a button that on click will set the toggle state to the opposite of the current toggle state.
we can see that when we hard refresh the page the useEffect still runs cause it is console logging the "useEffect running". The useEffect is running on a hard refresh despite having a condition, which doesn't match our use case, we need to run the useEffect on every time the user clicks on the button.
But luckily we have a workaround here.
what we have done here is, we got a new state init with default value true. Now when we do a hard refresh the useEffect will run and it will check if init is true, if it is true it will setinit to false. Now that init is false on every consecutive click on the button it will change the toggle value, which will trigger the useEffect and will console log "useEffect running". With this workaround, we can prevent the useEffect to stop triggering events on every hard refresh even if we have a dependency .