My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
A Simple UseEffect trick

Photo by Joan Gamell on Unsplash

A Simple UseEffect trick

Gitartha Kashyap's photo
Gitartha Kashyap
·Feb 9, 2022·

2 min read

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.

Screenshot from 2022-02-09 10-57-37.png

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.

Screenshot from 2022-02-09 11-12-20.png

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 .