reactjsnext.js

Implement a server component in Next.js that dynamically changes


I need to implement a component in Next.js that shows two different texts based on the minutes of time, even minutes to show "Hi", odds minutes to show "Hello". But not in a client component, but in a server component.

I tried:

// ./components/MyComponent.jsx

const Component = ({ data }) => {
  return <>
    {new Date().getMinutes() % 2 === 0 ? "Hi" : "Hello"}
  </>
}

export default Component
// ./layouts/PostLayout.tsx

import MyComponentfrom '@/components/MyComponent.jsx'
// ..

export default function PostLayout({ content, authorDetails, next, prev, children }: LayoutProps) {
  // ..
  
  return (
    <>
      // ..
      <MyComponent data={""} />
      // ..
    <>
  )
}
// ..

but it seems the above calculates the value only the one time on the build time (I guess) and it only shows either "Hi" or "Hello" regardless of the minutes of time I reloaded the page.

So how can I it to work? (Note that I cannot use 'use client' because the delay time is crucial in the app)

// versions
"next": "13.5.6",

Thanks.


Solution

  • By default, Next.js caches static pages, so you need to opt out of caching.

    If you know what page the component is used on, you could include the Route Segment Config dynamic = 'force-dynamic' in your page.jsx:

    // page.jsx
    
    export const dynamic = 'force-dynamic';
    
    export default function Page() {
      return <PostLayout />
    }
    

    Alternatively, a server component can be switched to dynamic rendering by either using cookies() or headers() or using the unstable noStore() method:

    // ./component/MyComponent.jsx
    import { cookies, headers } from 'next/headers'
    import { unstable_noStore as noStore } from 'next/cache'
    
    const Component = ({ data }) => {
      let _ = cookies();
      // or
      let _ = headers();
      // or
      noStore();
    
      ...
    }