Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js - new Date() constructor throwing console errors

I'm trying to use new Date() constructor in Next.js react component. But its throwing below console errors on production.

This is how I'm using the date constructor.

date: "2022-06-21T18:30:00.000Z"

{new Date(date).toLocaleDateString("en-US")}

Uncaught Error: Minified React error #425; - https://reactjs.org/docs/error-decoder.html?invariant=425
Uncaught Error: Minified React error #418; - https://reactjs.org/docs/error-decoder.html?invariant=418
Uncaught Error: Minified React error #423; - https://reactjs.org/docs/error-decoder.html?invariant=423

Any idea why its happening. Helps would be appreciated. Thanks!

like image 330
Vivekraj K R Avatar asked Sep 19 '25 16:09

Vivekraj K R


1 Answers

As per @bcjohn's comment I have figured out that hydration errors can be fixed by formatting the date in useEffect instead of directly adding it in jsx.

Here's the custom hook that I written for formatted date.

import { useState, useEffect } from "react";

const useFormattedDate = (date) => {
  const [formattedDate, setFormattedDate] = useState(null);

  useEffect(
    () => setFormattedDate(new Date(date).toLocaleDateString("en-US")),
    []
  );

  return formattedDate;
};

export default useFormattedDate;

Sample usage

const date = useFormattedDate(obj.date);
like image 57
Vivekraj K R Avatar answered Sep 22 '25 07:09

Vivekraj K R