skip to Main Content

I’m using NextJS14 with the app router.
I want to create a game project.

Initially, a description of the game and a Start button are displayed. When the Start button is clicked, the description disappears and the game begins.

"use client";

import { useState } from "react";
import Game from "./Game";

export default function StartButton() {
  const [start, setStart] = useState(false);
  return (
    <>
      {!start && (
        <button
          onClick={() => {
            setStart(true);
          }}
        >
          Start
        </button>
      )}
      {start && <Game {...props} />}
    </>
  );
}

I would like the game description to be implemented using Server-Side Rendering (SSR) to enhance SEO. However, due to the need to handle the Start button click event, I am currently using useState.

However, implementing the code as described will result in all of it being rendered client-side (CSR).

How can I resolve the issue described above?
Thank you in advance for your help.

2

Answers


  1. Your component is still rendered by the server with whatever the default values for the useState are, it’s not entirely client-side rendered. The server is able to pre-render this component with its default values for SEO, only the dynamism is left out.

    Your current component tree can be generated to the following HTML:

    <body>
      <button>Start</button>
    </body>
    

    With that said, typically with Next.js you’ll want to organize your component tree in such a way that you minimize the use of 'use client' whenever you can, while maintaining your components as modular as possible.

    In your particular case, I’d recommend you think about your StartButton component since it’s not really just as a "start" button, it’s also handling the game rendering logic.

    While it doesn’t look too bad right now, it is better to have components do one thing and one thing well so any future changes do not hit you hard.

    Login or Signup to reply.
  2. To make the description be implemented using SSR, you can create a server-rendered component :

    import { Metadata } from 'next';
    
    export const metadata: Metadata = {
      title: 'Game Description',
      description: 'An exciting game where you can start by clicking the button below.',
    };
    
    export default function GameDescription() {
      return (
        <div>
          <h1>Game Description</h1>
          <p>This is an exciting game where you can test your skills and have fun!</p>
        </div>
      );
    }
    

    and call it inside your Game component :

    import GameDescription from './description/page';
    
    export default function Game() {
      return (
        <>
          <GameDescription />
          ...
        </>
      );
    }
    

    Start button component is fine and would work unchanged.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search