React TS setInterval state is not updated in the callback FIX

You can encounter some issues when trying to create a Interval, for example every 10 seconds check if the user made some changes.
The problem could be, that you can not allways get the current state from within the callback.
this is because React saves new value to the setState when it is updated and does not work by reference under the hood.

So how to use useState in Interval?

You have more than one option:

1. useInterval

this is the option that I find mostly suiting when dealing with this problem.
You can use the useInterval(callback, delay) function from react-use
or you can make the the function by yourself if you dont need any other functionality from react-use.

2. useRef

you can use the useRef instead of useState to get reference that is current

3. useStateRef

you can use also useStateRef to get the actual state

4. useState from setState

you can use the setState function to get the current value

let stateCopy = ""
  stateCopy = prevState
  return prevState
} )




Leave a Reply

Your email address will not be published. Required fields are marked *