...
Code Block | ||
---|---|---|
| ||
import React, { useState } from 'react' import { useEffect } from 'react'; function getTheTime() { let currentDate = new Date(); let currentTime = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return currentTime; } export default function FCDisplayTimeInSameSpot(){ console.log("Executing FCDisplayTimeInSameSpot()"); const [containerState, setContainerState] = useState(["<NO TIME SET>"]); const getDisplayData = () => { const cdata = containerState return cdata; } // This useEffect will only run once when the component is first mounted useEffect(()=>{ setInterval(()=>{ setContainerState(getTheTime()); }, 3000010000); }, []) // This useEffect will run every time the component re-renders useEffect(() =>{ console.log(getDisplayData()) }) // This useEffect will only run once when the component is first mounted useEffect(() =>{ console.log("mounting the FCDisplayTimeInSameSpot"); }, []); // This useEffect will run every time the component is unmounted useEffect(() =>{ return ()=>console.log("unmounting the FCDisplayTimeInSameSpot"); }); return ( <> <p>Time is - {getDisplayData()}</p> </> ) } |
...
Notice that the component method is always called. In actual fact, the useState() methods are called each time the component method is called, therefore resetting the state variable back to its initial value. To see this at work, modify the useEffect() call at 22-26 so the following
Code Block | ||
---|---|---|
| ||
// This useEffect will only run once when the component is first mounted
useEffect(()=>{
setInterval(()=>{
const timeStamp = containerState;
setContainerState(getTheTime());
}, 30000);
}, []) |
The timeStamp
variable serves no real purpose except to allow us to put a breakpoint in the code and examine the values in the variables. I've also changed the timer from 10 seconds to 30 seconds to give us time to examine the variables.
Set a breakpoint on the timeStamp variable. When the code breaks, hover your mouse over timeStamp
it should be undefined. Step over it and it should be set to <NO TIME SET>
. This is the initial value from the useState()
call.
So what are we seeing here? Whenever the component’s state changes (achieved by modifying any of its state variables through their setter methods), the component method will be called and useState()
will be called re-initialising the variable. So we need to make use of the useEffect()
method during the component's lifecycle.
If you want data to persist across component renders, you need to use useRef()
. We'll cover this in another section