'NextJS - new Date cached on server

i am trying to always get a now Date on my server, but it get a cached date. I use yarn export to upload my files on a hosting server via ftp.

My code is:

export function MyComponent() {
    const now = new Date();
    return (
        <div>{now.getDate()}/{now.getMonth()+1}/{now.getFullYear()}</div>
    );
}

But when i render my component, it always come in a cached value. What am i missing?

  • Update, as juliomalves asked:

      import { useEffect,useState } from 'react';
      export function MyComponent() {
          const [now, setNow] = useState(new Date());
          useEffect(() => {
              setNow(new Date());
          },[])
          return (
              <div>{now.getDate()}/{now.getMonth()+1}/{now.getFullYear()}</div>
          );
      }
    


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source