In my React application, I'm trying to make some text dynamic based on the current user's time, utilizing the Date object in JS. For example, new Date().getHours().
When it is 11:59am, I want the text "Morning" to be rendered, but AS SOON as the time changes to 12:00pm, I want "Afternoon" to be rendered to the screen.
Currently, I have the following implementation using setInterval and checking the current hour every second, I believe this is not the best way as it is calling the useEffect hook too frequently? But without this setInterval, I have to refresh the page to see the new changes. Is there a better way to do this?
export const myFunction = () => {
const [myText, setMyText] = useState("");
const [localTime, setLocalTime] = useState(new Date().getHours());
useEffect(() => {
function timeInterval() {
const currentHour = new Date().getHours();
if (localTime !== currentHour) {setLocalTime(currentHour);}
if (localTime >= 1 && localTime < 12) {setMyText("Morning");}
else if (localTime >= 12 && localTime < 17) {setMyText("Afternoon");}
}
timeInterval();
const myInterval = setInterval(timeInterval, 1000);
return () => clearInterval(myInterval);
}, [myText, localTime]);
return (
<h1>
{myText}
</h1>
);
}