Reputation: 167
I have a react component to which we are passing isAlive
as a prop which has an initial value as false
from the parent component, I have an indefinite setInterval
which console.log
whether the person is alive or not. As and when the prop is getting updated the latest value is not getting reflected in the set interval at run time and it's retaining the original value always which is false
.
const printUserStatus = ({isAlive}) =>{
setInterval(() => {
if(isAlive === false){
console.log("the user is Dead");
}
else if(isAlive === true){
console.log("the user is Alive");
}
},1000);
}
UPDATE: Thanks to mahdi approach, have solved it by the following way -
const printUserStatus = ({isAlive}) =>{
const isAliveRef = useRef(isAlive);
isAliveRef.current = isAlive;
setInterval(() => {
if(isAliveRef.current === false){
console.log("the user is Dead");
}
else if(isAliveRef.current === true){
console.log("the user is Alive");
}
},1000);
}
Upvotes: 1
Views: 479
Reputation: 1450
Check this 6 years old answer about how setInterval
work
https://stackoverflow.com/a/19123476/13647574
use something like useRef()
to avoid this
Upvotes: 1
Reputation: 3253
If you intentionally want to read the latest state from some asynchronous callback, you could keep it in a ref, mutate it, and read from it.
Check out React Docs.
Basically the value you see is the value of the isAlive
when the function was first called.
Upvotes: 2