Home > other >  new Date(); in React causing loop and CRASH. why?
new Date(); in React causing loop and CRASH. why?

Time:02-11

import React, { useState, useEffect } from "react";

import "./Date.css";
import "./Home.css";

export default function Date(props) {
  const [dateState, setDateState] = useState(new Date());
  useEffect(() => {
    setInterval(() => setDateState(new Date()), 30000);
  }, []);
  if (props.active) {
    return (
      <div className="Date popup">
        <p>TODAYS DATE WILL GO HERE</p>
        <p>
          {" "}
          {dateState.toLocaleDateString("en-GB", {
            day: "numeric",
            month: "short",
            year: "numeric",
          })}
        </p>
        <p>THE TIME WILL GO HERE HH:MM:SS</p>
        <p>
          {dateState.toLocaleString("en-US", {
            hour: "numeric",
            minute: "numeric",
            hour12: true,
          })}
        </p>
      </div>
    );
  } else return null;
}

I am trying to implement the javascript Date() method in React and no matter what when I try it, it makes the app crash. I am getting an error in the console.

Uncaught RangeError: Maximum call stack size exceeded

Even if I try to do something simple like below, it still crashes.

let now = new Date();
console.log(now) 

link to repo https://github.com/mariaalouisaa/3-in-1-react.git

Thanks in advance!

CodePudding user response:

You declare Date name for your function component.(that is same as JavaScript Date function name!) And you call it in your function component that is created an infinite loop! Rename your function component.

  • Related