I am trying to detect if the page number (which is created by useState hook) has changed in last 5 seconds to make a conditional if statement. Is this possible in React/JavaScript?
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
One option might be to update the state you have that probably looks something like this:
To something like this:
This way, every time you update
page
, you also updatelastUpdated
, so you can do something like:You can also store the
lastUpdated
value in a new state piece if you can’t or don’t want to change the one you already have.Also, you can potentially use
setInterval
to continuously updateupdatedWithinTheLastFiveSeconds
(if you want to implement something like a progress bar) or just usesetTimeout
if you just need to know when the 5 seconds have passed, like in the example below:You can use "useEffect" with "useState". Create one useState variable for storing the lastupdation time stamp so that you can compare it with the latest time and check whether the difference is more than 5 second or not
Then you can use isPageChanged variable for any condition