Skip to content
Advertisement

React – not able to access latest props value inside setInterval

Actually trying to access props inside the setInterval but it’s not giving the latest value. Please find the below. From the parent component, I am passing time and updating time after 1 ms initially it will be null.

In child component after 2 ms i am trying to access latest value from the props but its holds the older value which is null.

Please find the code below

JavaScript
JavaScript

Thanks in advance. Happy coding!!

Advertisement

Answer

I’m not sure why you’d don’t want to use state because it looks to be the far easier solution. setInterval seems to be very unpredictable.

Note: you should be passing in props.updatedTime as a dependency to the useEffect. But, now, because you know that the time is changing every second you can keep a count within state and just trigger the condition in the effect when it reaches 2.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement