skip to Main Content
import React, { useState, useEffect } from 'react';

function DigitalClock() {
  const[currentTime, setCurrentTime] = useState(new Date());
  useEffect(()=>{
    const interval = setInterval(()=>{
      setCurrentTime(new Date());
    },1000);
    return () => clearInterval(interval);
  },[]);
  useEffect(()=>{
    const second = currentTime.getSeconds();
    if(second===0){
      console.log("another minute passed");
    }
  },[currentTime])
  const formattedTime = currentTime.toLocaleTimeString();
  return(
    <h2>{formattedTime}</h2>
  )
}

export default DigitalClock;

IN THIS I WANT TO MAKE A CONSOLE.LOG AFTER EVERY MINUTE PASSED, BUT IT ONLY PRINTS THE FIRST MINUTE.

I want to know how to solve this issue, and how does useEffect hooks work in Reactjs.

2

Answers


  1. you can modify the useEffect hook to check if the seconds value is divisible by 60 .
    you can use this code:

    function DigitalClock() {
      const [currentTime, setCurrentTime] = React.useState(new Date());
    
      React.useEffect(() => {
        const interval = setInterval(() => {
          setCurrentTime(new Date());
        }, 1000);
    
        return () => clearInterval(interval);
      }, []);
    
      React.useEffect(() => {
        const seconds = currentTime.getSeconds();
        if (seconds % 60 === 0 && seconds !== 0) {
          console.log('Another minute passed');
        }
      }, [currentTime]);
    
      const formattedTime = currentTime.toLocaleTimeString();
    
      return <h2>{formattedTime}</h2>;
    }
    
    ReactDOM.render(<DigitalClock />, document.querySelector('.react'));
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <div class='react'></div>
    Login or Signup to reply.
  2. I believe you do not need two useEffect to do this. Follow an example:

    function DigitalClock() {
      const [currentTime, setCurrentTime] = React.useState(null);
    
      React.useEffect(() => {
        const interval = setInterval(() => {
          const date = new Date();
          const formattedTime = date.toLocaleTimeString();
          
          setCurrentTime(formattedTime);
        }, 1000);
    
        return () => clearInterval(interval);
      }, []);
    
      return <h2>{currentTime}</h2>;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search