Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs - Call function on startup of application with a functional component

My application displays a greeting such as "Good Morning" depending on the time of day. I have a function that checks the time and changes the greeting based on what time it is. I can't use componentDidMount since it's a functional component, so I'm using React.useEffect. The issue is this does not run on startup, there is a small delay where the app displays "Good Morning" and then will change to "Good Afternoon". How can I remove this delay.

Function that determines greeting based on time

const [currGreeting, setCurrGreeting] = useState(greetings[0]);

//Involves saving to localStorage so the transition can be seamless if the app is exited and returned to

function updateGreeting(){
  time = new Date();
    
  let hour = time.getHours();

  console.log(hour);

  if(12 > hour && hour > 5){
    setCurrGreeting(greetings[0]);
    console.log("Good Morning")

    const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
    if(curSessionGreeting != currGreeting){
      localStorage.setItem("sessionGreeting", JSON.stringify(greetings[0]));
      setCurrGreeting(greetings[0]);
    }
  }
  if((18 > hour && hour > 12) || hour === 12){
    setCurrGreeting(greetings[1]);
    console.log("Good Afternoon")

    const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
    if(curSessionGreeting != currGreeting){
      localStorage.setItem("sessionGreeting", JSON.stringify(greetings[1]));
      setCurrGreeting(greetings[1]);
    }
  }
  if(hour > 18 || (5 > hour && hour > 0)){
    setCurrGreeting(greetings[2]);
    console.log("Good Evening")

    const curSessionGreeting = JSON.parse(localStorage.getItem("sessionGreeting")) || [];
    if(curSessionGreeting != currGreeting){
      localStorage.setItem("sessionGreeting", JSON.stringify(greetings[2]));
      setCurrGreeting(greetings[2]);
    }
  }
}

Updates the greeting

React.useEffect(() => {
  setInterval(()=>updateGreeting(), 1000);
});

Where the app is rendering

return (
<div> 
  <div style = {{display: 'flex', fontFamily: 'Work Sans', fontSize: 25,marginBottom: 25, color: '#CDCACA'}}>
    <text>{currGreeting}</text>
   </div> 
 </div> 
 );
};

export default App;
like image 973
Sachu Avatar asked Sep 13 '25 18:09

Sachu


1 Answers

You should run one updateGreeting before executing setInterval since this delay the first updateGreeting execution one second 1000msit does that asynchronously :


React.useEffect(() => {

   updateGreeting()//first execution
  
   setInterval(()=>updateGreeting(), 1000);
},[]);
like image 96
Boussadjra Brahim Avatar answered Sep 16 '25 08:09

Boussadjra Brahim