You can add expired property for model and set set it to true when the time coms
const [model, setModel] = useState<Expirable>({
expiredAt: new Date((new Date).getTime() + 20000)
expired: false
});
// You can also use useRef instead of useState here.
const [expirationTimeoutId] = useState(() =>{
return setTimeout(() =>{
// setModel on currentModel to have last value of model
setModel(currentModel => ({...currentModel, expired: true }))
}, model.expiredAt - Date.now())
});
// You should clear timeout when the component is unmounted
useEffect(() =>{
return () => clearTimeout(expirationTimeoutId)
},[])
return (
{ model.expired ? (
<Text>Expired</Text>
) : (
<Text>Not Expired</Text>
)}
);
Updated: If you don't want to touch model you can do this
const [model, setModel] = useState<Expirable>({
expiredAt: new Date((new Date).getTime() + 20000)
});
const [isModelExpired, setIsModelExpired] = useState(false)
const [expirationTimeoutId] = useState(() =>{
return setTimeout(() =>{
setIsModelExpired(true)
}, model.expiredAt - Date.now())
});
// You should clear timeout when the component is unmounted
useEffect(() =>{
return () => clearTimeout(expirationTimeoutId)
},[])
return (
{ isModelExpired ? (
<Text>Expired</Text>
) : (
<Text>Not Expired</Text>
)}
);