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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With