I get a warning " Can't perform a React state update on an unmounted component " when i am running this code
function timer() {
const [dateState, setDateState] = useState(new Date());
useEffect(() => {
setInterval(() => setDateState(new Date()), 1000);
}, []);
return(
<div className="container">
<p className="text-end text-danger">{dateState.toLocaleDateString('fr-BE' , {
day : 'numeric',
month : 'short',
year: 'numeric'
})}</p>
<div className="text-center">
<h3 className="text-info">
{dateState.toLocaleString('fr-BE', {
hour: 'numeric',
minute: 'numeric',
second : 'numeric',
hour24: true,
})}
</h3>
</div>
</div>
)
}
export default timer;
I tried to do
const [dateState, setDateState] = useState(new Date());
useEffect(() => {
let mount = true;
if(mount){
setInterval(() => setDateState(new Date()), 1000);
}
return () => { isMounted = false };
}, []);
But still not working, i'm kind of stuck...
You need to cleanup the setInterval timer on component unmount, like:
useEffect(() => {
const interval = setInterval(() => setDateState(new Date()), 1000);
return () => {
clearInterval(interval);
}
}, []);