I have a state value, it may change from time to time. I want to have a flag that indicate "this state has been staying in value x without any changes for y amount of time"
How do I achieve this?
P.S, if you played Oxygen Not Included, this is the logic I want: https://oxygennotincluded.fandom.com/wiki/FILTER_Gate
Update: can't use setInterval/polling for this.
The code in this answer is available at https://stackblitz.com/edit/react-qjmyix?file=src%2FApp.js
The function
useStateWithTimeFlagin the snippet below, returns an object with functions identical to those ofsetState, as well as a function for getting the elapsed time, and a variable with the elapsed time.You can use whichever you prefer.
The first
useEffecthook updates theElapsedTimevariable once every second.The second hook resets the timer, whenever the state changes.
This components shows how the function can be used.